0

我在它的语句中创建了一个动态WHERE子句它已成功创建,但我得到的输出为 0。有什么想法我错了吗?SELECTStored ProcedureSQL SERVER 2008-R2.

这是我的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
4

1 回答 1

2

任何想法我错了?

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

我相信这会让你感兴趣。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
于 2013-02-16T08:42:01.840 回答