您將需要做的是創建動態SQL併爲每個ListType構建額外的CASE語句。我不得不做類似的工作,他們想要了解有關事件的某些信息。這些事件將以逗號分隔列表的形式傳遞,然後構建案例陳述。
我已經從一個逗號創建一個表中的存儲過程分隔列表
CREATE PROCEDURE [dbo].[ListToTable]
@vcList VARCHAR(8000),
@vcDelimiter VARCHAR(8000),
@TableName SYSNAME,
@ColumnName SYSNAME
AS
SET NOCOUNT ON
DECLARE @iPosStart INT,
@iPosEnd INT,
@iLenDelim INT,
@iExit INT,
@vcStr varchar(8000),
@vcSql varchar(8000)
SET @iPosStart = 1
SET @iPosEnd = 1
SET @iLenDelim = LEN(@vcDelimiter)
SET @vcSql = 'INSERT ' + @TableName + ' (' + @ColumnName + ') VALUES ('''
SET @iExit = 0
WHILE @iExit = 0
BEGIN
SET @iPosEnd = CHARINDEX(@vcDelimiter, @vcList, @iPosStart)
IF @iPosEnd <= 0
BEGIN
SET @iPosEnd = LEN(@vcList) + 1
SET @iExit = 1
END
SET @vcStr = SUBSTRING(@vcList, @iPosStart, @iPosEnd - @iPosStart)
EXEC(@vcSql + @vcStr + ''')')
SET @iPosStart = @iPosEnd + @iLenDelim
END
RETURN 0
那麼這裏就是動態SQL
DECLARE @Events VARCHAR(8000) = 'Event1,Event2,... Eventn'
CREATE TABLE #Events
(
EventName VARCHAR(MAX)
)
EXEC [ListToTable]
@Events
,','
,'#Events'
,'EventName'
DECLARE @strCASE VARCHAR(MAX)
SET @strCase = ''
DECLARE Events_Cursor CURSOR
FOR
SELECT EventName FROM [#Events]
OPEN Events_Cursor
DECLARE @EventName VARCHAR(MAX)
FETCH NEXT FROM Events_Cursor INTO @EventName
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
SET @strCase = @strCase + ',CASE WHEN [EventOpportunityProduct].[Name] = ''' + @EventName + ''' THEN EventOppertunityLineItem.[Trial_Status__c] ELSE NULL END [' + @EventName + ']'
FETCH NEXT FROM Events_Cursor INTO @EventName
END
CLOSE Events_Cursor
DEALLOCATE Events_Cursor
然後加入@strCASE到你的SELECT語句前。
DECLARE @strSQL VARCHAR(MAX)
SET @strSQL = 'SELECT
Field1
,Field2
' + @strCASE + '
FROM Table'
EXEC (@strSQL)