2010-03-30 227 views
1

我有一個項目表具有以下的列交叉表查詢

ProjectID, ProjectDescription 

,並具有以下各列的列表數據表

ProjectID ListType Date Memo 

每個項目都有在ListType表許多列表類型條目。

我想要做的是運行一個查詢將返回這樣的事情

ProjectID, ProjectDescription, ListType1, ListType1.date, Listtype1.Memo, ListType2, ListType2.date, ListType.Memo 

Againg,每一個項目都是coonected到一個號碼列表類型的數據。 我正在使用Microsoft SQL 2000.所以Pivot關鍵字不起作用

回答

0

您將需要做的是創建動態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)