sql 将许多行连接成单个文本string.sql

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 将许多行连接成单个文本string.sql相关的知识,希望对你有一定的参考价值。

SET NOCOUNT ON;  

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

create table #Temp
(
	NodeName VARCHAR(1000),
	Date VARCHAR(100),
	Content VARCHAR(8000),
	Names VARCHAR(8000),
	Expertise VARCHAR(8000),
	Publication VARCHAR(8000),
	Office VARCHAR(8000)
)

DECLARE @NodeId int
DECLARE @Names VARCHAR(8000)
DECLARE @Expertise VARCHAR(8000)
DECLARE @NodeName VARCHAR(1000)
DECLARE @Date VARCHAR(100)
DECLARE @Content VARCHAR(8000)
DECLARE @Publication VARCHAR(8000)
DECLARE @Office VARCHAR(8000)
DECLARE News_Cursor CURSOR FOR   
    Select 
        NodeID
    From 
        HDY_NewsItem as News
        Inner Join View_CMS_Tree_Joined as Tree on Tree.DocumentForeignKeyValue = News.NewsItemID
    Where
        Tree.ClassName = 'HDY.NewsItem'

OPEN News_Cursor  

FETCH NEXT FROM News_Cursor   
    INTO @NodeId

WHILE @@FETCH_STATUS = 0  
BEGIN 
	
	select @NodeName = Tree.NodeName, @Date = news.ArticleDate, @Content = news.NewsCopy
	From 
        HDY_NewsItem as News
        Inner Join View_CMS_Tree_Joined as Tree on Tree.DocumentForeignKeyValue = News.NewsItemID
    Where
        Tree.ClassName = 'HDY.NewsItem' and NodeID = @NodeId

	SELECT 
		@Names = COALESCE(@Names + ', ', '') + NodeName 
	From 
		CMS_Relationship as crl
		inner join View_CMS_Tree_Joined as ct on crl.RightNodeID = ct.NodeID
	where LeftNodeID = @NodeId and RelationshipNameID = 3
	
	SELECT @Expertise = COALESCE(@Expertise + ', ', '') + NodeName
	from CMS_Relationship as crl
	inner join View_CMS_Tree_Joined as ct
	on crl.LeftNodeID = ct.NodeID
	where RightNodeID = @NodeId and RelationshipNameID = 4

	SELECT 
		@Publication = COALESCE(@Publication + ', ', '') + NodeName
	From 
		CMS_Relationship as crl
		inner join View_CMS_Tree_Joined as ct on crl.RightNodeID = ct.NodeID
	where LeftNodeID = @NodeId and RelationshipNameID = 6

	SELECT 
		@Office = COALESCE(@Office + ', ', '') + NodeName 
	From 
		CMS_Relationship as crl
		inner join View_CMS_Tree_Joined as ct on crl.RightNodeID = ct.NodeID
	where LeftNodeID = @NodeId and RelationshipNameID = 7

	Insert into #Temp values (@NodeName, @Date, @Content, @Names, @Expertise, @Publication, @Office)
	set @NodeName = ''
	set @Date = ''
	set @Content = ''
	set @Names = ''
	set @Expertise = ''
	set @Publication = ''
	set @Office = ''
	FETCH NEXT FROM News_Cursor   
		INTO @NodeId

END

CLOSE News_Cursor
DEALLOCATE News_Cursor  

Select * From #Temp

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End
DECLARE @Names VARCHAR(8000) 
SELECT @Names = COALESCE(@Names + ', ', '') + Name
FROM People
WHERE Name IS NOT NULL

以上是关于sql 将许多行连接成单个文本string.sql的主要内容,如果未能解决你的问题,请参考以下文章

如何在 SQL Server 中将多行文本连接成单个文本字符串

SQL将多行左连接成一行

Oracle/SQL:将日期和时间连接成单个日期值时的数字格式模型无效

VBA将许多变量连接成字符串

如何从1个表中选择许多行并将其插入另一个表中特定行的特定JSONB字段中?但是在单个原始SQL查询中

通过 Netezza 查询将行折叠成单个字段