1

我有这个存储过程

USE [all_things]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_getThingsByType]
    @thingid int,
    @typeid int
AS

DECLARE @Sql NVARCHAR(MAX) = 'SELECT * from items'

IF @thingid IS NOT NULL
BEGIN
  SET @Sql += ' where thingid = @thingid'
END

IF @typeid IS NOT NULL
BEGIN
  SET @Sql += ' and TypeID = @typeid'
END

EXEC sp_executesql @sql, N'@thingid int,@typeid int',@thingid=@thingid,@typeid=@typeid;

测试用例:

  1. 当我用thingidisnulltypeidis运行它时null,我得到了所有完美的结果。

  2. thingid提供了并且typeidnull时,结果是好的

  3. 这是结果不好的地方:thingidisnulltypeidis 供应。一切都在归还。

我错过了什么?

谢谢

4

1 回答 1

1

感谢@tschmit007,我修复了它。

USE [all_things]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_getThingsByType]
    @thingid int,
    @typeid int
AS

DECLARE @Sql NVARCHAR(MAX) = 'SELECT * from items'

IF @thingid IS NOT NULL
BEGIN
  SET @Sql += ' where thingid = @thingid'
END

IF @typeid IS NOT NULL AND @thingid IS NOT NULL
BEGIN
  SET @Sql += ' and TypeID = @typeid'
END

IF @typeid IS NOT NULL AND @thingid IS NULL
BEGIN
  SET @Sql += ' where TypeID = @typeid'
END

EXEC sp_executesql @sql, N'@thingid int,@typeid int',@thingid=@thingid,@typeid=@typeid;
于 2013-04-04T15:40:14.667 回答