So, I’ve come across a pretty annoying problem with T-SQL… Essentially, in a table, there are several T-SQL statements. I want a stored procedure to efficiently grab these rows and concatenate them to a variable. Then, execute the concatenated lines with EXEC(@TSQL)
The problem is, string concatenation with newlines seem to be stripped when calling Exec…
For example something like:
declare @sql nvarchar(max) = ''
select @sql += char(13) + char(10) + [sql] from [SqlTable]
exec(@sql) -- Won't always do the right thing
print @sql -- Looks good
I don’t want to butcher the code with a Cursor, is there any way around this? Thanks!
Edit:
Okay, so it looks like the issue is in fact only with the GO statement, for example:
declare @test nvarchar(max) = 'create table #test4(i int) ' + char(10) + char(13) + 'GO' + char(10) + char(13) +'create table #test5(i int)'
exec(@test)
I guess this go will have to go (no pun intended) I just really didn’t want to have to try and parse it in fear of special cases blowing up the whole thing.
A
selectstatement withoutorder byis free to return results in any order.You’d have to specify the order in which your SQL snippets make sense:
As @Bort suggested in the comments, if the snippets are stand-alone SQL, you can separate them with a semicolon. Carriage returns, newlines, tabs and spaces are all the same in T-SQL: they’re whitespace.