Avatar of Leo Torres
Leo Torres
Flag for United States of America asked on

Dynamic SQL query with Columns

Trying to run this code not sure why i am getting an error

Declare @sql nvarchar(4000), @Table varchar(25), @BatchNo varchar(25)
, @BatchCol varchar(25),@IDColumn varchar(25), @Max int, @Loopcount int
,@returnValue int, @Statement nvarchar(4000)

set @Statement = N'
SELECT @result = Count(1) 
from [CKOLTP_Staging].dbo.[@TableValue] tbl (nolock)
where tbl.[@BatchColValue] = Convert(varchar(10),@BatchNoValue)'
exec sp_executesql @Statement, 
    N'@TableValue varchar(25)
	,@BatchColValue varchar(25) 
	,@BatchNoValue varchar(25)
	,@result INT OUTPUT', 
    @TableValue = @Table
	,@BatchColValue = @BatchCol
	,@BatchNoValue = @BatchNo 
	,@result=@returnValue OUTPUT    

Open in new window



Error
Msg 208, Level 16, State 1, Line 5
Invalid object name 'CKOLTP_Staging.dbo.@TableValue'.

Open in new window


Can we not have the column as a variable?
Microsoft SQL ServerMicrosoft SQL Server 2008SQL

Avatar of undefined
Last Comment
Leo Torres

8/22/2022 - Mon
SOLUTION
Brian Crowe

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Scott Pletcher

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Leo Torres

ASKER
Yes, I ended up doing that. I didnt know you cant do this with objects
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23