sqlserver列轉行例項(只需要 修改其中幾個欄位 就可以直接使用)
首先建立表
CREATE TABLE [dbo].[ColumnIpParameter] (
[ColumnIp_ip] int IDENTITY(1,1) NOT NULL,
[Columnlp_typeid] int NULL,
[Columnlp_Listing] varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
[Columnlp_port] varchar(50) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK_ColumnIpParameter] PRIMARY KEY CLUSTERED ([ColumnIp_ip])
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
)
ON [PRIMARY]
GOALTER TABLE [dbo].[ColumnIpParameter] SET (LOCK_ESCALATION = TABLE)
ColumnIp_ip | Columnlp_typeid | Columnlp_Listing | Columnlp_port |
---|---|---|---|
1 | 1 | IP地址 | 127.0.0.1 |
2 | 1 | 埠 | 8080 |
3 | 1 | 子網掩碼 | 255.255.255.0 |
4 | 1 | 閘道器地址 | 127.0.0.254 |
5 | 1 | MAC地址 | 00:00:00:00:00 |
修改 儲存過程名字(ColumnIp) 行轉列表(ColumnIpParameter) 分組欄位(Columnlp_typeid) 行變列的欄位(Columnlp_Listing) 行變列值的欄位(Columnlp_port) 這幾個欄位 就可以使用了 需要在SQL Server Management Studio裡面使用,不要在
ALTER PROCEDURE ColumnIp
//如果不需要帶引數,那就不需要寫
AS
BEGIN
DECLARE @sql_str NVARCHAR(MAX)
DECLARE @sql_col NVARCHAR(MAX)
DECLARE @sql_where NVARCHAR(MAX)
DECLARE @tableName SYSNAME --行轉列表
DECLARE @groupColumn SYSNAME --分組欄位
DECLARE @row2column SYSNAME --行變列的欄位
DECLARE @row2columnValue SYSNAME --行變列值的欄位
SET @tableName = 'ColumnIpParameter'
SET @groupColumn = 'Columnlp_typeid'
SET @row2column = 'Columnlp_Listing'
SET @row2columnValue = 'Columnlp_port'
SET @sql_where = 'WHERE Columnlp_typeid = 1'--從行資料中獲取可能存在的列
SET @sql_str = N'
SELECT @sql_col_out = ISNULL(@sql_col_out + '','','''') + QUOTENAME(['[email protected]+'])
FROM ['[email protected]+'] GROUP BY ['[email protected]+']'
--PRINT @sql_str
EXEC sp_executesql @sql_str,N'@sql_col_out NVARCHAR(MAX) OUTPUT',@[email protected]_col OUTPUT
--PRINT @sql_colSET @sql_str = N'
SELECT * FROM (
SELECT ['[email protected]+'],['[email protected]+'],['[email protected]+'] FROM ['[email protected]+']'[email protected]_where+') p PIVOT
(max(['[email protected]+']) FOR ['[email protected]+'] IN ( '+ @sql_col +') ) AS pvt
ORDER BY pvt.['[email protected]+']'
--PRINT (@sql_str)
EXEC (@sql_str)
END
執行例項 SQL Server Management Studio 查詢裡面執行
下面是執行效果
參考 https://www.cnblogs.com/liangqihui/p/6718896.html 並進行了優化