简体   繁体   English

SQL Server 2008 Management Studio串联行

[英]SQL Server 2008 Management Studio concatenating rows

I have been working on this for about 2 days, and I can not for the life of me understand what I am doing wrong. 我已经为此工作了大约2天,我一生无法理解我在做什么错。 Basically, I am trying to take a temporary table that I have made (which I have already combined the columns for). 基本上,我试图获取一个临时表(已将其合并为该表)。 Now I am trying to combine the rows, and after 20 solid hours of searching I can not find the solution. 现在,我正在尝试合并行,经过20个小时的搜索,我找不到解决方案。 I'm hoping someone can explain to me what I am doing wrong. 我希望有人可以向我解释我做错了什么。

I am using Microsoft SQL Server 2008 Management Studio. 我正在使用Microsoft SQL Server 2008管理Studio。

DECLARE @ThisUID int;
DECLARE @ThisUIDName varchar;

SELECT TOP 1 @ThisUIDName = ElementName 
FROM ElementNames 
WHERE ElementUID = @ThisUID

;WITH CTE AS (
    SELECT v.ElementUID, 
    '^'+a.ElementAttribute + '|' + Value1 + Value2 as Combined 
    FROM ElementAttributeValues v 
    Left JOIN ElementAttributes a 
    ON v.ElementAttribute = a.UID 
)
SELECT * 
INTO #TempTable 
FROM CTE 

SELECT 
    a.ElementUID, a.Combined
    STUFF((SELECT CAST( '' as varchar(max)) + e.Combined
           FROM #TempTable
           WHERE e.ElementUID = a.ElementUID
           FOR xml path(''), type). as a.Combined
FROM #TempTable a
ORDER BY a.ElementUID DESC

If any can explain what is doing horribly wrong for me I would be most appreciative. 如果有什么可以解释我的所作所为非常糟糕,那我将非常感激。

First of all, I don't see a comma (,) after the first line in your final SELECT statement (after a.Combined), and secondly, I think it's really bad idea to also call the value of the STUFF statement the same - .. as a.Combined - try to use distinct names 首先,在最终的SELECT语句的第一行之后(在a.Combined之后),我看不到逗号(,);其次,我认为也将STUFF语句的值也设为相同是一个很糟糕的主意-.. as a.Combined-尝试使用不同的名称

So try this as your final SELECT statement: 因此,请尝试将其作为您的最终SELECT语句:

SELECT 
    a.ElementUID, a.Combined,   -- add a comma at the end of this line
    STUFF((SELECT CAST('' AS VARCHAR(MAX)) + e.Combined
           FROM #TempTable
           WHERE e.ElementUID = a.ElementUID
           FOR XML PATH(''), TYPE) AS Stuffed     -- use a distinct name here!
FROM #TempTable a
ORDER BY a.ElementUID DESC

I think your are not passing the exact number of arguments to your stuff function. 我认为您没有将确切数量的参数传递给您的填充函数。 stuff accepts 4 arguments. 东西接受4个参数。 STUFF ( character_expression , start , length , replaceWith_expression ) STUFF(character_expression,start,length,replaceWith_expression)

even as marc mentioned comma is missed, extra . 即使marc提到了逗号,也没错。 after type) is there 输入后)在那里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM