如何在varchar变量中插入SQL查询的结果? [英] How can I insert the result of a SQL query in a varchar variable?

查看:97
本文介绍了如何在varchar变量中插入SQL查询的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题:



执行此查询:



Hi, this is my question:

I execute this query:

SELECT CODE FROM MyTable 





结果如下:



CODE

1

2

5

9



怎么样我将结果插入varchar变量?:



@ CODES ='1,2,5,9'



我想一行一行FOR循环,但我不知道怎么做。



谢谢。



This is the result:

CODE
1
2
5
9

How can I insert the result in a varchar variable?:

@CODES='1,2,5,9'

I thought go row by row with a "FOR" cycle, but I don't know how to do it.

thanks.

推荐答案

您实际上可以使用COALESCE来执行此操作。如果你谷歌搜索sql concatenate rows你会得到很多例子:



例如:

You can actually use COALESCE to do this. If you google for "sql concatenate rows" you get lots of examples:

For example:
DECLARE @Codes NVARCHAR(MAX) 
SELECT @Codes = COALESCE(@Codes + ', ', '') + Code
FROM MyTable


Yeaaahhh !!!那就是解决方案!非常感谢Ryan。 :D



由于Code字段被声明为整数,我不得不做一点改动,我必须将这个字段转换为Varchar,就是这样:


Yeaaahhh !!! that's the solution!!! a lot of thanks Ryan. :D

I had to do a little change because "Code" field was declared as integer, I had to convert this field to a Varchar and that's it:

this is my Solution:

DECLARE @Codes NVARCHAR(MAX) 

SELECT @Codes = COALESCE(@Codes + ', ', '') + CONVERT(varchar,Code)
FROM MyTable

SELECT @Codes


这篇关于如何在varchar变量中插入SQL查询的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆