'动态'存储过程

时间:2013-12-20 17:55:49

标签: stored-procedures sql-server-2012

我对存储过程非常陌生,需要一些帮助。

我正在尝试创建一个“动态”存储过程。当参数为NOT NULL时,应添加SQL的某个部分。这就是我现在所拥有的。

    SELECT        
    TCId, 
    ENVId, 
    UId, 
    MTId, 
    TestSetName, 
    TestCaseName, 
    InterchangeSeqNo, 
    InstructionSeqNo, 
    TransactionSeqNo, 
    TestCaseDescription
FROM XML_TEST_SET_OVERVIEW
WHERE (ENVId = @MyENVId)
SELECT CASE @MyUId 
    WHEN IS NOT NULL THEN (AND UId = @MyUId)
END
SELECT CASE @MyMTId
    WHEN IS NOT NULL THEN (AND MTId = @MyMTId)
END
SELECT CASE @MyTestSetName
    WHEN IS NOT NULL THEN (AND TestSetName = @MyTestSetName) 
END
SELECT CASE @MyTestCaseName
    WHEN  IS NOT NULL THEN  (AND TestCaseName = @MyTestCaseName) 
END
SELECT CASE @MyInterchangeSeqNo
    WHEN  IS NOT NULL THEN  (AND InterchangeSeqNo = @MyInterchangeSeqNo) 
END
SELECT CASE @MyInstructionSeqNo
    WHEN  IS NOT NULL THEN (AND InstructionSeqNo = @MyInstructionSeqNo) 
END
SELECT CASE @MyTransactionSeqNo
    WHEN  IS NOT NULL THEN (AND TransactionSeqNo = @MyTransactionSeqNo)
END  
ORDER BY ENVId, UId, MTId, TestSetName, TestCaseName, InterchangeSeqNo, InstructionSeqNo, TransactionSeqNo

感谢任何帮助

1 个答案:

答案 0 :(得分:1)

我必须在这里猜测数据类型,并且我会让你填补额外的毛病。

DECLARE @sql NVARCHAR(MAX) = N'SELECT ... 
  FROM dbo.XML_TEST_SET_OVERVIEW -- always use schema prefix
  WHERE ENVId = @MyENVId'

    + CASE WHEN @MyUId IS NOT NULL THEN 
           N' AND UId = @MyUId' ELSE '' END
    + CASE WHEN @MyMTId IS NOT NULL THEN 
           N' AND MTId = @MyMTId' ELSE '' END
    + CASE WHEN @MyTestSetName IS NOT NULL THEN 
           N' AND TestSetName = @MyTestSetName' ELSE '' END 
      ...
    + CASE WHEN @MyTransactionSeqNo IS NOT NULL THEN
           N' AND TransactionSeqNo = @MyTransactionSeqNo' ELSE '' END

    + N' ORDER BY ENVId, UId, ...;';

EXEC sp_executesql @sql, 
    N'@MyENVId INT, @MyUId INT, @MyMTId INT, 
      @MyTestSetName NVARCHAR(32), ... , @MyTransactionSeqNo INT',
    @MyENVId, @MyUId, @MyMTId, @MyTestSetName, ... , @MyTransactioNSeqNo;