我正在使用VS2005 C#和SQL2005。
我想从多个列中检索数据并合并它们,并用逗号分隔它们。
例如。我的SQL表UserData中的数据:No. | Username | Role 1 | Role 2 | Role 3 |
1 | Jimmy | USER | READONLY | WRITE |
我想在GridView GridView1中显示的数据:No. | Username | Roles |
1 | Jimmy | USER, READONLY, WRITE |
如何使用SELECT语句合并3列中的数据并合并它们,用逗号分隔数据并在GridView中列出它们?
谢谢
编辑
我尝试使用Shark和Mun提供的方法,但是如果Role列中的数据为空,我想删除逗号。
现在的情况是,如果角色2和角色3为空,则Roles
列将如下所示:USER,,
我可以知道如何将,
分组为变量,以便如果该值为空将不会显示?
最佳答案
这是SQL查询:
select
username,
isnull(nullif([role 1], '') + ', ', '') +
isnull(nullif([role 2], '') + ', ', '') +
isnull(nullif([role 3], ''), '') as Roles
from UserData
然后为您的网格视图代码:
SqlConnection conn = new SqlConnection(YourConnectionStringHere);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText =
"select " +
" username, " +
" isnull(nullif([role 1], '') + ', ', '') + " +
" isnull(nullif([role 2], '') + ', ', '') + " +
" isnull(nullif([role 3], ''), '') as Roles " +
"from UserData";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Datatable YourData = new DataTable();
try
{
sda.Fill(YourData);
GridView1.DataSource = YourData;
GridView1.Bind();
}
catch
{
sda.Dispose();
// handle your error
}
关于c# - 从多列中检索数据并在单列中显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8752505/