我在之前的一个问题中已经回答了这个问题,但现在我有了另一个问题。我正在尝试创建一个视图,并且已经帮助创建了以下查询;
DECLARE @table TABLE
(
[Type_ID] INT,
[Client_ID] VARCHAR(50),
[PBX_Vendor] VARCHAR(50)
)
INSERT INTO @table
SELECT dbo.AMGR_User_Fields_Tbl.Type_Id, dbo.AMGR_User_Fields_Tbl.Client_Id, dbo.AMGR_User_Field_Defs_Tbl.Description AS PBX_Vendor
FROM dbo.AMGR_User_Fields_Tbl INNER JOIN
dbo.AMGR_User_Field_Defs_Tbl ON dbo.AMGR_User_Fields_Tbl.Type_Id = dbo.AMGR_User_Field_Defs_Tbl.Type_Id AND
dbo.AMGR_User_Fields_Tbl.Code_Id = dbo.AMGR_User_Field_Defs_Tbl.Code_Id
WHERE (dbo.AMGR_User_Fields_Tbl.Type_Id = 127)
SELECT [Type_ID],
[Client_ID],
(
SELECT STUFF((
SELECT ', ' + [PBX_Vendor]
FROM @table
WHERE [Client_ID] = tbl.[Client_ID]
AND [Type_ID] = tbl.[Type_ID]
GROUP BY [PBX_Vendor]
ORDER BY [PBX_Vendor]
FOR
XML PATH('')
), 1, 1, '')
) PBX_Vendor
FROM @table tbl
GROUP BY [Type_ID],
[Client_ID]
这给了我需要的结果,并将列的结果放在同一个单元格中。但是当我保存视图时,我得到“关键字DECLARE附近的语法不正确”。我理解我不能在视图中运行Declare,那么我可以选择运行什么替代方案?它必须是一种观点。
答案 0 :(得分:0)
答案 1 :(得分:0)
我可能会在这里遗漏一些东西,但你为什么不这样做?
WITH ctetable
AS (SELECT dbo.AMGR_User_Fields_Tbl.Type_Id,
dbo.AMGR_User_Fields_Tbl.Client_Id,
dbo.AMGR_User_Field_Defs_Tbl.Description AS PBX_Vendor
FROM dbo.AMGR_User_Fields_Tbl
INNER JOIN dbo.AMGR_User_Field_Defs_Tbl
ON dbo.AMGR_User_Fields_Tbl.Type_Id =
dbo.AMGR_User_Field_Defs_Tbl.Type_Id
AND dbo.AMGR_User_Fields_Tbl.Code_Id =
dbo.AMGR_User_Field_Defs_Tbl.Code_Id
WHERE ( dbo.AMGR_User_Fields_Tbl.Type_Id = 127 ))
SELECT [Type_ID],
[Client_ID],
(SELECT Stuff((SELECT ', ' + [PBX_Vendor]
FROM ctetable
WHERE [Client_ID] = tbl.[Client_ID]
AND [Type_ID] = tbl.[Type_ID]
GROUP BY [PBX_Vendor]
ORDER BY [PBX_Vendor]
FOR xml path('')), 1, 1, '')) PBX_Vendor
FROM ctetable tbl
GROUP BY [Type_ID],
[Client_ID]
您可以详细了解CTE here。
使用公用表表达式
公用表表达式(CTE)可以被认为是在单个SELECT,INSERT,UPDATE,DELETE或CREATE VIEW语句的执行范围内定义的临时结果集。 CTE类似于派生表,因为它不作为对象存储,并且仅在查询期间持续。与派生表不同,CTE可以是自引用的,并且可以在同一查询中多次引用。