Dynamic Sql has its own scope, any variables declared outside of its scope are not visible to dynamic sql, You declare any passing variable in second parameter to sp_executesql
and if you are expecting to store and retrieve a value from that variable pass it as an OUTPUT
variable using the key work OUT
or OUTPUT
.
Also use QUOTENAME()
function around your Sql Server Object names when concatenating them into strings. Protects you against sql injection attack.
See below....
DECLARE @Strings NVARCHAR(MAX);
DECLARE @Sql NVARCHAR(MAX);
DECLARE @BlaTableName NVARCHAR(128) = N'Table_Name'
SET @Sql = N'SELECT @Strings = COALESCE(@Strings + '','', '''','''') + CAST(Name AS NVARCHAR(MAX))
FROM ' + QUOTENAME(@BlaTableName) + N' order by Name'
EXEC sp_executesql @Sql
,N'@Strings NVARCHAR(MAX) OUT' --<-- you need to declare variable here
,@Strings OUTPUT
SELECT @Strings --<-- Test it