mssql, I need to set a varchar = every field in a row, delineated by a character
I have a table that has 4 rows, the first to ID them, and the other 3 to store data.
E.G.
ID ROW1 ROW2 ROW3
1 AB EF NG
2 CD GH OU
3 JK
4 LH
I have three variables, let's say, @return1, @return2, and @return3, and I want to set them equal to every value in rows 1, 2, and 3, delineating the values by ';'.
E.G.
[some code here that I'm having trouble figuring out, this is what I need help with
Produces this result:
@return1 = AB; CD;
@return2 = EF; GH; JK; LH;
@return3 = NG; OU;
Thanks so much for looking! I'm sure there is an easy and elegant way to loop through each row and accomplish this, I'm just having a bi开发者_StackOverflow中文版t of a time figuring out the right way to do this.
If anyone could point me in the right direction about how to do this select, or how to loop through these, that would be excellent!
Example
DECLARE @return1 VARCHAR(Max)
SELECT @return1 = ''
SELECT @return1 = @return1 + coalesce(ROW1 + '; ' ,'')
FROM SomeTable
Same for the other variables
See also here for an example by using FOR XML PATH Concatenate Values From Multiple Rows Into One Column if you need the results ordered, there are examples you can run
DECLARE @return1 VARCHAR(MAX) = ''
DECLARE @return2 VARCHAR(MAX) = ''
DECLARE @return3 VARCHAR(MAX) = '';
WITH YourTable(ID, ROW1, ROW2, ROW3) AS
(
SELECT 1,'AB','EF','NG' UNION ALL
SELECT 2,'CD','GH','OU' UNION ALL
SELECT 3,NULL,'JK',NULL UNION ALL
SELECT 4,NULL,'LH',NULL
)
SELECT
@return1 = @return1 + ISNULL(ROW1 + ';',''),
@return2 = @return2 + ISNULL(ROW2 + ';',''),
@return3 = @return3 + ISNULL(ROW3 + ';','')
FROM YourTable
select @return1,@return2,@return3
You should be aware that the above isn't absolutely guaranteed to work but in current versions it tends to work as long as you aren't performing additional operations on the input that would change the compute scalar location in the plan.
精彩评论