从表中选择,然后在存储过程中形成一个以空格分隔的字符串

时间:2022-06-01 20:49:55

I want to select about 4-5 rows from a table, then form a space separated string.

我想从表中选择大约4-5行,然后形成一个空格分隔的字符串。

All of this is to be done in a stored procedure (SQL server 2005).

所有这些都是在存储过程中完成的(SQL server 2005)。

Is this possible?

这可能吗?

I will then use this space-separated string and save it to another table.

然后我将使用这个以空格分隔的字符串并将其保存到另一个表中。

Update

SELECT *
FROM Users
WHERE userID < 10

output:

john
jake
blah
sam

So, put this in a space separated string:

所以,把它放在一个空格分隔的字符串中:

'john jake blah sam'

'john jake blah sam'

and save that string to another row in a table.

并将该字符串保存到表中的另一行。

All this has to be done in a stored procedure (if possible).

所有这些都必须在存储过程中完成(如果可能)。

2 个解决方案

#1


3  

DECLARE @firstnames varchar(max)

SELECT 
    @firstnames = COALESCE(@firstnames + ' ', '') + FirstName 
FROM 
    Users 
WHERE 
    UserId < 10

INSERT INTO OtherTable (OtherColumn) VALUES (@firstNames)

#2


0  

I think something like this will work:

我觉得这样的事情会起作用:

DECLARE @whatever varchar(max)  -- or varchar(1000) or whatever size
SET @whatever = ''

SELECT @whatever = @whatever + MyColumn + ' ' FROM MyTable

#1


3  

DECLARE @firstnames varchar(max)

SELECT 
    @firstnames = COALESCE(@firstnames + ' ', '') + FirstName 
FROM 
    Users 
WHERE 
    UserId < 10

INSERT INTO OtherTable (OtherColumn) VALUES (@firstNames)

#2


0  

I think something like this will work:

我觉得这样的事情会起作用:

DECLARE @whatever varchar(max)  -- or varchar(1000) or whatever size
SET @whatever = ''

SELECT @whatever = @whatever + MyColumn + ' ' FROM MyTable