我是SQL Server的新手,有两个select语句 - 我正在尝试将UNION结合起来。 但是我收到错误消息= 为变量赋值的SELECT语句不能与数据检索操作结合。
如何分配@NEWComments变量??
DECLARE @NEWComments VARCHAR(max)
SELECT @NEWComments
select cast(Comments1 as varchar(max)),cast( Comments2 as varchar(max)),
cast(Comments3 as varchar(max)),
from TableComments
where CommentsID = 1234
UNION
SELECT TOP 2 @NEWComments = COALESCE(@NEWComments,'') +
cast(comments as varchar(max)) + ';'
FROM [ChildTableComments]
where CommentsID = 1234
请帮助!!
我正在尝试从两个表TableComments和ChildTableComments中检索记录。 TableComments将具有atmax 1记录,但ChildTableComments将具有相同CommentsID的许多记录。
所以我试图从ChildTableComments获取Top2记录并添加它们并返回1个单独的列,可以使用UNION添加TableComments。
答案 0 :(得分:2)
如果要将所有子注释合并为一行,可以这样做:
DECLARE @NEWComments VARCHAR(max);
SET @NEWComments = '';
SELECT TOP 2 @NEWComments = @NEWComments + COALESCE(comments,'')
FROM [ChildTableComments]
where CommentsID = 1234;
select cast(Comments1 as varchar(max)) AS com1,
cast( Comments2 as varchar(max)) as com2,
cast(Comments3 as varchar(max)) as com3
from TableComments
where CommentsID = 1234
UNION
SELECT @NEWComments AS com1,
null as com2,
null as com3;
答案 1 :(得分:1)
您也可以尝试使用此
DECLARE @NEWComments VARCHAR(max);
SELECT TOP 2 @NEWComments = @NEWComments + COALESCE(comments,'')
FROM [ChildTableComments] where CommentsID = 1234;
select @NEWComments AS Comments, cast(Comments1 as varchar(max)) AS com1,
cast( Comments2 as varchar(max)) as com2,
cast(Comments3 as varchar(max)) as com3
from TableComments where CommentsID = 1234
答案 2 :(得分:0)
我不确定你要做什么。但UNION
必须具有相同数量的列。我没有得到你想要做的任务。但这是一个可行的建议。我不确定Comments2
陈述中Comments3
和UNION
应该是什么:
DECLARE @NEWComments VARCHAR(max)
SELECT @NEWComments
select
cast(Comments1 as varchar(max)) Comments1,
cast(Comments2 as varchar(max)) Comments2,
cast(Comments3 as varchar(max)) Comments3,
from
TableComments
where
CommentsID = 1234
UNION
SELECT TOP 2
COALESCE(@NEWComments,'') + cast(comments as varchar(max)) + ';' AS Comments1,
'???' AS Comments2,
'???' AS Comments3
FROM [ChildTableComments]
where CommentsID = 1234