动态Where子句:没有输出

时间:2013-02-16 07:25:03

标签: sql-server-2008-r2 dynamic-sql

我在WHERE中的SELECT语句中创建了一个动态Stored Procedure子句SQL SERVER 2008-R2.它已成功创建,但输出为0.任何想法我在哪里错?

这是我的SP:

CREATE PROCEDURE [dbo].[SPData]
@Id int = NULL,
@Requester varchar(20) = NULL,
@Suggester varchar(20) = NULL
AS
BEGIN
DECLARE @sql nvarchar(4000)
SELECT @sql=' [Id], [Suggester], [Requester] from CRM.dbo.Request_Table WHERE 1=1 '
If (@Id) IS NOT NULL
        SELECT @sql=@sql + ' AND Id=(@Id) '
If (@Suggester) IS NOT NULL
        SELECT @sql=@sql + ' AND Suggester like (@Suggester) '
If (@Requester) IS NOT NULL
        SELECT @sql=@sql + ' AND Requester like (@Requester) '
END
GO

1 个答案:

答案 0 :(得分:2)

  

我错的任何想法?

构建动态SQL后,还必须使用sp_executesql执行它。

我相信这会让你感兴趣。 Dynamic Search Conditions in T-SQL

ALTER PROCEDURE [dbo].[SPData]
@Id int = NULL,
@Requester varchar(20) = NULL,
@Suggester varchar(20) = NULL
AS
BEGIN
DECLARE @sql nvarchar(4000)
SELECT @sql='SELECT [Id], [Suggester], [Requester] from CRM.dbo.Request_Table WHERE 1=1 '
If (@Id) IS NOT NULL
        SELECT @sql=@sql + ' AND Id=(@Id) '
If (@Suggester) IS NOT NULL
        SELECT @sql=@sql + ' AND Suggester like (@Suggester) '
If (@Requester) IS NOT NULL
        SELECT @sql=@sql + ' AND Requester like (@Requester) '

EXEC sp_executesql @sql, 
                   N'@id int, @Requester varchar(20), @Suggester varchar(20)', 
                   @Id, @Requester, @Suggester

END