gunnerz
gunnerz

Reputation: 1926

String concatenation in Dynamic SQL

I want to pass a parameter to a stored procedure which contains dynamic SQL.

For example,

DECLARE @sql NVARCHAR(1000)
SET @sql = 'select '+ @columnnames + ' from tablename'
EXECUTE(@sql)

But @columnnames is a string created at runtime, by concatenating 2 strings
like @columnnames = a + ' ' + b

However this does not seem to work. I think I need to escape the single quotes. I have tried passing
a + \' \' + b , but that doesn't work either.

Any suggestions?

Upvotes: 1

Views: 4505

Answers (2)

Nikola Markovinović
Nikola Markovinović

Reputation: 19346

declare @columnnames nvarchar(1000)
set @columnnames = 'a' + ' + '' '' + ' + 'b'

produces

select a + ' ' + b from tablename

Use apostrophe twice when you need apostrophe in resulting varchar .

Upvotes: 6

freefaller
freefaller

Reputation: 19953

You're missing a comma...

set @columnnames = a + ',' + b

Upvotes: 0

Related Questions