Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

„Dynamische“ gespeicherte Prozedur

Ich muss hier Datentypen erraten, und ich überlasse es Ihnen, den zusätzlichen Fluff einzutragen.

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;