我正在尝试创建一个动态数据透视表,但它一直告诉我"你必须声明表变量@ venta"。
这是代码,我做错了什么?
DECLARE @venta TABLE
(
LAPSO_DOC CHAR(6),
ID_EXT_ITM CHAR(3),
ID_TALLA CHAR(6),
VENTA INT
)
INSERT INTO @venta
VALUES
('201601', 'VER', 'L', '20'),
('201603', 'ROJ', 'XL', '40'),
('201604', 'NEG', 'S', '60'),
('201608', 'BLA', 'M', '80');
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SELECT @columns=STUFF ((SELECT DISTINCT'],['+ LAPSO_DOC
FROM @venta
GROUP BY '],['+LAPSO_DOC FOR XML PATH('') ),1,2,'')+']'
SET @sql = 'SELECT
(
SELECT LAPSO_DOC,ID_EXT_ITM,ID_TALLA,VENTA
FROM @venta
)
PIVOT
(
SUM(CANTIDAD_CAP) FOR LAPSO_DOC IN ('+@columns+')
) AS y;';
EXECUTE (@sql)
答案 0 :(得分:3)
这是一个范围问题。
表变量不适用于动态sql
也许把它放到临时表
答案 1 :(得分:2)
您的查询问题比您预期的要多......
CREATE TABLE #venta (
LAPSO_DOC char(6),
ID_EXT_ITM char(3),
ID_TALLA char(6),
VENTA int
)
INSERT INTO #venta
VALUES ('201601', 'VER', 'L', '20'),
('201603', 'ROJ', 'XL', '40'),
('201604', 'NEG', 'S', '60'),
('201608', 'BLA', 'M', '80');
DECLARE @columns nvarchar(max),
@sql nvarchar(max);
SELECT
@columns = STUFF((SELECT DISTINCT
'],[' + LAPSO_DOC
FROM #venta
GROUP BY '],[' + LAPSO_DOC
FOR xml PATH (''))
, 1, 2, '') + ']'
SET @sql = 'SELECT ID_EXT_ITM,ID_TALLA,' + @columns + '
FROM #venta
PIVOT
(
SUM(VENTA) FOR LAPSO_DOC IN (' + @columns + ')
) AS y;';
EXEC (@sql)
DROP TABLE #venta