如何通过sql语句把字典值转换成字符串类型
如
1,2,3,4,5,6
1,2,5
1 张三
2 王二
3 李四
4 麻子
5 小明
6 小红
转换成
张三、王二、李四、麻子、小明、小红
张三、王二、小明
通过sql server语句实现
你好,可以用decode()函数,主要作用:将查询结果翻译成其他值(即以其他形式表现出来,以下举例说明);
使用方法:
Select decode(columnname,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)
from talbename
其中columnname为要选择的table中所定义的column,
·含义解释:
decode(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)的理解如下:
if (条件==值1)
then
return(翻译值1)
elsif (条件==值2)
then
return(翻译值2)
......
elsif (条件==值n)
then
return(翻译值n)
else
return(缺省值)
end if
注:其中缺省值可以是你要选择的column name 本身,也可以是你想定义的其他值,比如Other等;
如下图:自己把字段名和表名替换了就能实现,列名需要重新显示则在 ) 后面 as 需要的字段名; 如符合需求请点击下采纳
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Q717309
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext db = new DataClasses1DataContext();
var query = db.Table1s.AsEnumerable().SelectMany(x => x.value.Split(',')
.Select(y => new { x.id, y = db.Table2s.AsEnumerable().Single(z => z.id.ToString() == y.Trim()).text.Trim() }))
.GroupBy(x => x.id)
.Select(x => new { id = x.Key, value = string.Join(",", x.Select(y => y.y)) });
foreach (var item in query)
Console.WriteLine(item.id + " " + item.value);
}
}
}
定义字典: SQL语句使用 case when then end 就可以解决了
通过动态SQL可以实现。可以写个函数包装一下,用起来更方便。
参考:
declare @S nvarchar(max) = '';
select @S = @S + [Name] + ','
from sj_enumvalue
where [Value] in (101,102,103)
select LEFT(@S, LEN(@S)-1);
decode 和case when then 都可以实现
建字典表:
create table zidian (id tinyint,name nvarchar(30))---放123456对应名称
建立拆分函数:
CREATE FUNCTION [dbo].SplitStringToTable ,
@split VARCHAR(10)
)
RETURNS TABLE
AS
RETURN
( SELECT B.id
FROM ( SELECT [value] = CONVERT(XML , '' + REPLACE(@str , @split , '')
+ '')
) A
OUTER APPLY ( SELECT id = N.s.value('.' , 'varchar(100)')
FROM A.[value].nodes('/s') N ( s )
) B
)
如果你不在乎顺序:
declare @i as nvarchar(max)=''
select @i=@i+b.name+',' from zidian b left join (select dbo.SplitStringToTable('1,2,3,4,5,5,3,2',',') a on a.id=b.id
set @i=replace((@i+','),',,','')
select @i
在乎顺序:
declare @i as nvarchar(max)=''
select @i=@i+b.name+',' from zidian b cross apply (select * from dbo.SplitStringToTable('1,2,3,4,5,5,3,2',',')) a where a.id=b.id
set @i=replace((@i+','),',,','')
select @i
怕你还不懂,加上这一段,你想配合字段字符串的话就这样:
create table zifuchuan (c nvarchar(500))---字符串表
update zifuchuan set c=c+',0'---分行标识为0,且对应字典上为0字符加上!号对应关系
declare @i as nvarchar(max)=''
select @i=@i+b.name+',' from zidian b cross apply (select id from zifuchuan ab cross apply dbo.SplitStringToTable(ab.c,',') abc) a where a.id=b.id
select * from dbo.SplitStringToTable(replace(@i+';',',!,;',''),',!,')