-- 建立表
IF OBJECT_ID('VrveisConfigKeyValue',N'U') IS NULL
BEGIN
CREATE TABLE [dbo].[VrveisConfigKeyValue](
[ID] [INT] IDENTITY(1,1) NOT NULL,
[KeyName] [VARCHAR](100) NOT NULL,
[KeyValue] [TEXT] NULL,
[TypeName] [VARCHAR](100) NOT NULL,
[UserID] [INT] NOT NULL,
[ExField1] [INT] NULL,
[ExField2] [INT] NULL,
[Reserved1] [VARCHAR](500) NULL,
[Reserved2] [VARCHAR](500) NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GOsql
/*
*
*<參數化動態PIVOT行轉列,帶條件查詢的參數化動態PIVOT行轉列>
*
*/
DECLARE @sql_str NVARCHAR(MAX)
DECLARE @sql_col NVARCHAR(MAX)
DECLARE @sql_where NVARCHAR(MAX)
DECLARE @tableName SYSNAME --行轉列表
DECLARE @showColumns SYSNAME --顯示列
DECLARE @pivotColumn SYSNAME --行變列的字段
DECLARE @pivotColumnValue SYSNAME --行變列值的字段(聚合函數使用)函數
DECLARE @groupTable SYSNAME -- 行變列列的查詢表table
DECLARE @groupWhere SYSNAME -- 行變列分組條件im
SET @tableName = 'VrveisConfigKeyValue AS v LEFT JOIN dbo.Class AS c ON c.ClassID=v.ExField1'
SET @showColumns = 'v.ExField1 AS ClassID,v.KeyName,v.ExField2,c.ClassName'
SET @pivotColumn = 'KeyName'
SET @pivotColumnValue = 'ExField2'
SET @sql_where = 'WHERE v.TypeName=''ZJSELECTVALUE'' AND v.Reserved1=''201805'' '數據
--從行數據中獲取可能存在的列
SET @groupTable='VrveisConfigKeyValue'查詢
SET @groupWhere='WHERE TypeName=''ZJSELECTVALUE'' AND Reserved1=''201805'' and KeyName <>''AQZSStatistics'' and KeyName<>''YJLYStatistics'' 'db
SET @sql_str = N'
SELECT @sql_col_out = ISNULL(@sql_col_out + '','','''') + QUOTENAME(['+@pivotColumn+'])
FROM ['+@groupTable+'] '+@groupWhere+' GROUP BY ['+@pivotColumn+']'
--PRINT @sql_str
EXEC sp_executesql @sql_str,N'@sql_col_out NVARCHAR(MAX) OUTPUT',@sql_col_out=@sql_col OUTPUT
--PRINT @sql_col -- 打印行轉列的列值img
SET @sql_str = N'
WITH TempDetail
AS (
SELECT '+@showColumns+' FROM '+@tableName+' '+@sql_where+'
)
SELECT * FROM TempDetail PIVOT(MAX('+@pivotColumnValue+') FOR '+@pivotColumn+' IN ('+@sql_col+')) AS T
'
-- PRINT (@sql_str)
EXEC (@sql_str)
tab