使用Sp_executesql的动态SQL

时间:2013-09-11 12:03:46

标签: sql sql-server dynamic

我有一个存储过程,我必须使用sp_executesql重写。我想使用sp_executesql而不是exec,因为我的SQL Server实例存在性能问题。

这是我的代码:

ALTER PROCEDURE [dbo].[sp_TestSp1] 
      @Type1 VARCHAR(256)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @sqlCommand varchar(2000) = ''
    DECLARE @columnList varchar(1000) = ''
    DECLARE @dynamicSql varchar(1000) = ''

    IF  (@Type1 IS NOT NULL )
    BEGIN
    SET @dynamicSql = @dynamicSql + 'AND tbl1.DTypeID IN ( '+ @Type1+ ' )' 
    END     

SET @columnList = 'SELECT DISTINCT tbl2.ID, Name AS PName '
SET @sqlCommand =  @columnList 
                    + ' FROM tbl1 '
                    + ' INNER JOIN tbl3 ON tbl1.NID= tbl3.NID '
                    + ' INNER JOIN tbl4 ON tbl3.DID = tbl4.DID '
                    + ' WHERE TT=1 AND IsActive=1 AND tbl1.DTypeID IN (1,3,5)' 
                    + @dynamicSql
EXEC (@sqlCommand)

1 个答案:

答案 0 :(得分:1)

用以下内容替换您的EXEC(@sqlCommand)语句。

EXECUTE sp_executesql @sqlCommand

TechNet Link