我可以在查询中显示统计列,例如第1列,第2列,第3列....等等。
但我想这样做是动态的。
我的数据如下:
我希望能够执行存储过程来获取输出结果: 执行sp_output 1 (从另一个窗口,其中'1'代表PoolID(@AppPool)),如下所示:
这是我的SP:
create PROCEDURE [dbo].[sp_test]
@Query as nvarchar(100) -- OUTPUT?,
@AppPool AS nvarchar(50)
AS
SELECT @Query = Attribute FROM [dbo].[Vy_UserAccess] WHERE PoolID = @AppPool
SELECT [Users],'+ @Query +' FROM
(SELECT [Pool],[Users],[RecNum],[Attribute],[Values] FROM [dbo].[Vy_UserAccess] ) AS T1
PIVOT (MAX([Values]) FOR [ATTRIBUTE] IN ('+ @Query +')) AS T2
这可以通过微调我的代码来实现,还是我必须转向另一个方向?
答案 0 :(得分:1)
你可以在下面这样做:
<强> QUERY 强>
CREATE PROCEDURE [dbo].[sp_test]
@AppPool AS NVARCHAR(60)
AS
DECLARE @cols AS NVARCHAR(MAX) = '',
@sql AS NVARCHAR(MAX)
SELECT @cols += QUOTENAME([Name]) + ','
FROM (SELECT DISTINCT Attribute as Name
FROM [dbo].[Vy_UserAccess]
WHERE PoolID = @AppPool
) a
ORDER BY Name DESC
SET @cols = LEFT(@cols, LEN(@cols) - 1)
SET @sql = 'SELECT Users, ' + @cols + ' FROM
(
SELECT [Pool],[Users],[RecNum],[Attribute],[Values]
FROM [dbo].[Vy_UserAccess]
) AS T1
PIVOT (MAX([Values]) FOR [ATTRIBUTE] IN ('+ @cols +')) AS T2'
EXEC sp_executesql @sql, N'@AppPool NVARCHAR(60)', @AppPool
<强> EXECUTION 强>
Exec sp_test 1
查询样本数据
CREATE PROCEDURE sp_test
@AppPool AS NVARCHAR(60)
AS
CREATE TABLE #test
(
PoolId NVARCHAR(60),
Pool NVARCHAR(40),
Users NVARCHAR(60),
RecNum INT,
Attribute NVARCHAR(40),
[Values] NVARCHAR(20)
)
INSERT INTO #test VALUES
('1', 'FINANCE', 'User1', 2, 'DIVISION', '010'),
('1', 'FINANCE', 'User1', 1, 'COMPANY', '1'),
('1', 'FINANCE', 'User1', 1, 'DIVISION', '050')
DECLARE @cols AS NVARCHAR(MAX) = '',
@sql AS NVARCHAR(MAX)
SELECT @cols += QUOTENAME([Name]) + ','
FROM (SELECT DISTINCT Attribute as Name
FROM #test
WHERE PoolID = @AppPool
) a
ORDER BY Name DESC
SET @cols = LEFT(@cols, LEN(@cols) - 1)
SET @sql = 'SELECT Users, ' + @cols + ' FROM
(
SELECT [Pool],[Users],[RecNum],[Attribute],[Values]
FROM #test
) AS T1
PIVOT (MAX([Values]) FOR [ATTRIBUTE] IN ('+ @cols +')) AS T2'
EXEC Sp_executesql @sql, N'@AppPool NVARCHAR(60)', @AppPool
DROP TABLE #test
<强>输出强>
Users DIVISION COMPANY
User1 050 1
User1 010 NULL