我有一个包含以下列的项目表
ProjectID, ProjectDescription
和列表数据表,其中包含以下列
ProjectID ListType Date Memo
每个项目在ListType表中都有许多列表类型条目。
我想要做的是运行一个返回类似
的查询ProjectID, ProjectDescription, ListType1, ListType1.date, Listtype1.Memo, ListType2, ListType2.date, ListType.Memo
Againg,每个项目都与一些列表类型数据相关联。 我正在使用Microsoft SQL 2000.所以Pivot关键字不起作用
答案 0 :(得分: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)