Tuesday, May 20, 2008

Dynamic SQL in stored procedure

By using sp_executesql (system stored procedure), you can write the dynamic SQL inside the stored procedure.

sp_ExecuteSql accepts a list of parameters, the first two of which MUST be either ntext, nchar or nvarchar. The first is your sql statement and the second is the parameter names. The third part is the list of parameter values.

DECLARE @SqlString nvarchar(4000)
SET @SqlString = N'SELECT * FROM ' + @TableName + ' WHERE ID = @ID';
EXECUTE sp_executesql
,N'@ID int'

The @TableName and @ID are parameters passed into the stored procedure.

for more info, check:

No comments: