0

Suppose I want to select a constant value in an sql query, I could do something like this :

select name,age,'tick' from tableA

I want to dynamically generating an sql query using stored procedures. For example :

SELECT @SQL = 'SELECT CID,DOB, NAME, '+@Scname+' from ' + @TableName

Where @TableName, @Scname are dynamically generated variables in a while loop. Here @Scname is interpreted as a column name instead of a constant string when executing query on @TableName. I have tried using escape characters as follows :

SELECT @SQL = 'SELECT CID,DOB, NAME, \"'+@Scname+'\" from ' + @TableName

But it returns a floating point value full of zeros instead of the string contained in @Scname.

1
  • can you show the final @SQL ? Commented Feb 6, 2020 at 6:24

2 Answers 2

2

I think following should work

SET @SQL = 'SELECT CID,DOB, NAME,'+''''+@Scname+''''+' from '+ @TableName
Sign up to request clarification or add additional context in comments.

Comments

2

Try

SELECT @SQL = 'SELECT CID,DOB, NAME,' + QUOTENAME(@Scname, '''') + ' from ' + @TableName

1 Comment

Learned something new.

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.