从逗号分隔的字段读取SQL,然后以逗号分隔的格式返回数据

时间:2015-07-23 17:28:29

标签: sql-server tsql comma delimited

我在表格列中有字符串格式3,2,1的数据。我有查找表,告诉我与文件相关联的文件名

表格如下

Id (int) name
------------------
  1      file 1
  2      file 2

我想要做的是发送字符串3,2,1并将数据作为file 1, file 2作为单独的列返回,以便我可以在显示中引用它。请注意,这将添加到现有存储过程中,这就是为什么我只想要一个字符串行返回

提前感谢您的帮助

2 个答案:

答案 0 :(得分:0)

你可能想写一些像这样的代码。下面的代码只是让你走上正轨的一个例子。如果您有任何问题,请告诉我

DECLARE @input VARCHAR(MAX)
DECLARE @index1 INT
DECLARE @index2 INT
DECLARE @Id VARCHAR(10)
DECLARE @str VARCHAR(MAX)
DECLARE @result VARCHAR(MAX)

SET @input = '3,2,1';
SET @str = REVERSE(@input)
SET @index1 = 1;
SET @index2 = CHARINDEX(',', @str)
SET @Id = SUBSTRING(@str, @index1, @index2 -@index1)

SET @result = 'File ' + @Id + ','

WHILE (@index2 > 0 )
BEGIN

    SET @str = SUBSTRING(@str, @index2 + 1, LEN(@str) -@index1)
    SET @Id = SUBSTRING(@str,@index1,@index2 -@index1) 
    SET @index1 = @index2
    SET @index2 = CHARINDEX(',', @str)
    IF LEN(@Id) > 0
        SET @result = @result + 'File ' + @Id + ','
END

SET @Id = @str;
SET @result =  @result + 'File ' + @Id

SELECT @result

答案 1 :(得分:0)

另一个例子:

-- Create ID String, only used for example
DECLARE @IDString varchar(max)
set @IDString = '1,2,3,4'

-- Create lookup table, only used for example
CREATE TABLE #lookup (id int, val varchar(50))
INSERT INTO #lookup(id, val) VALUES (1, 'first lookup') 
INSERT INTO #lookup(id, val) VALUES (2, 'second lookup') 
INSERT INTO #lookup(id, val) VALUES (3, 'third lookup') 
INSERT INTO #lookup(id, val) VALUES (4, 'fourth lookup') 

-- Convert ID String to individual IDs        
DECLARE @Xml xml
SELECT @Xml = CONVERT(xml,' <root><id>' + REPLACE(@IDString,',','</id><id>') + '</id></root>')

-- Join IDs to lookup table and return string
SELECT SUBSTRING(
(SELECT ',' + Val as [text()]
FROM (SELECT ID = Tab.rec.value('.','varchar(20)') FROM @Xml.nodes('/root/id') Tab(rec)) ids
JOIN #lookup ON ids.ID = #lookup.id
FOR XML PATH('')),2,1000) AS valuestring

--Cleanup, only used for example
DROP TABLE #lookup