简体   繁体   中英

How can I assign multiple records from a select into one parameter in sql

Does anyone know how can I assign the multiple records from a select into one parameter in sql? Example:

I have the following select statement:

SELECT '|'+id+':'+rep
FROM dbo.reps

it will return the following result:

|1:tom
|2:amy
|3:ben
|4:ken

How can I assign those value into a parameter @rep and when I select @rept, it will display:

|1:tom|2:amy|3:ben|4:ken

will it possible?

One method is to use aggregate string concatenation (ala XML), but that is a hassle in SQL Server. Another is to use recursive CTEs.

The simplest method is:

DECLARE @rep varchar(max);
SET @rep = '';

SELECT @rep = (@rep + '|'+id+':'+rep0
FROM dbo.reps;

I am not sure if this is guaranteed to be supported (I haven't seen documentation that explicitly says yes or no on this), but it does generally work in SQL Server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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