有时候查询出的某一列结果要作为其他数据库查询条件,必须要做拼接转换
方法:
SELECT [id] = stuff((SELECT distinct ‘,‘‘‘ + t.id + ‘‘‘‘ FROM table t WHERE t.id = 1 FOR xml path (‘‘)),1,1,‘‘);
方法使用如下:
SELECT [Id] = STUFF((SELECT DISTINCT ‘,‘‘‘ + Ld + ‘‘‘‘ FROM BaseMeterFieldType AS b WHERE b.MeterId IN (SELECT Id FROM BaseTree WHERE CompanyId = ‘071B4795-E124-E711-80EA-C979862AE7CB‘) FOR xml PATH(‘‘)),1,1,‘‘);
执行结果:
以上报错是由于id为GUID,且id需要小写,所以需要进行类型转换,方法如下:
SELECT [Id] = STUFF((SELECT DISTINCT ‘,‘‘‘ + CAST(LOWER(b.Id) AS VARCHAR(4000)) + ‘‘‘‘ FROM BaseMeterFieldType AS b WHERE b.MeterId IN (SELECT Id FROM BaseTree WHERE CompanyId = ‘071B4795-E124-E711-80EA-C979862AE7CB‘) FOR xml PATH(‘‘)),1,1,‘‘);
执行结果:
原文地址:https://www.cnblogs.com/Damon-LLJ/p/11326402.html
时间: 2024-10-20 15:38:54