2011-10-12 14:09:00

Using Dynamic SQL to execute a SELECT statement

DECLARE @SQL AS VARCHAR(1000)

SET @SQL='SELECT * '
SET @SQL= @SQL _p_l_u_s_ 'FROM myTable'

EXEC (@SQL)

Dynamic SQL with return values

DECLARE @sql NVARCHAR(MAX) = 'SET @count = (SELECT * FROM sys.objects)'

DECLARE @count INT
EXEC sp_executeSQL @sql, N'@count INT OUTPUT', @count OUTPUT

PRINT @count

Notes

The statement and parameter must be an NVARCHAR or NCHAR.

In this case, @sql is the statement parameter.

in this case, N'@count INT OUTPUT' is the parameter. Remember N is the NVARCHAR attribute.

Copyright © 2024 delaney. All rights reserved.