2

pass column name & value dynamically and get result of query into another variable.

@ColumnName , @SKU_ID are input variables, output data store into @ColumnValue variable.
DECLARE @ColumnName
char(50)
DECLARE @SKU_ID
varchar(50)
DECLARE @ColumnValue
varchar(150)
DECLARE @Sqlcommand
nvarchar(1000)
DECLARE @ColumnData
varchar(50)

SET @ColumnName = 'Color_Code'
SET @SKU_ID  = 'W16933'

SET @Sqlcommand = 'SELECT @ColumnData ='+@ColumnName+ 'FROM Stagetable WHERE SKU_ID = @SKU_ID' 
exec sp_executesql @Sqlcommand, N'ColumnData varchar(50) out' , @ColumnValue out

I'm getting below Error

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'ColumnData'. Msg 137, Level 15, State 1, Line 1 Must declare the scalar variable "@ColumnData". please help me out.

0

1 Answer 1

1

You need to prefix the variable declaration with an @

exec sp_executesql 
    @Sqlcommand, 
    N'@ColumnData varchar(50) out, @SKU_ID varchar(50)' , 
    @ColumnValue out, @SKU_ID
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.