我有这个存储过程
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;
测试用例:
当我使用thingid
null
并且typeid
为null
来运行时,我得到的结果非常完美。
提供thingid
且typeid
为null
后,结果还可以
以下是结果不佳的结果:thingid
为null
并提供了typeid
。一切都在归还。
我错过了什么?
由于
答案 0 :(得分: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;