sql server存储过程sp_executesql

时间:2013-04-04 15:23:57

标签: sql-server stored-procedures

我有这个存储过程

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. 当我使用thingid null并且typeidnull来运行时,我得到的结果非常完美。

  2. 提供thingidtypeidnull后,结果还可以

  3. 以下是结果不佳的结果:thingidnull并提供了typeid。一切都在归还。

  4. 我错过了什么?

    由于

1 个答案:

答案 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;