首先创建表
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里面使用,不要在Navicat Premium 12里面使用,因为有一些函数使用不了(亲测);
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(['+@row2column+'])
FROM ['+@tableName+'] GROUP BY ['+@row2column+']'
--PRINT @sql_str
EXEC sp_executesql @sql_str,N'@sql_col_out NVARCHAR(MAX) OUTPUT',@sql_col_out=@sql_col OUTPUT
--PRINT @sql_colSET @sql_str = N'
SELECT * FROM (
SELECT ['+@groupColumn+'],['+@row2column+'],['+@row2columnValue+'] FROM ['+@tableName+']'+@sql_where+') p PIVOT
(max(['+@row2columnValue+']) FOR ['+@row2column+'] IN ( '+ @sql_col +') ) AS pvt
ORDER BY pvt.['+@groupColumn+']'
--PRINT (@sql_str)
EXEC (@sql_str)
END
运行实例 SQL Server Management Studio 查询里面运行
下面是运行效果
参考 https://www.cnblogs.com/liangqihui/p/6718896.html 并进行了优化