如何将[0,3,4]转换为SQL Server 2012中6位字符串格式的100110?

时间:2017-11-17 05:43:43

标签: sql-server format

如何将[0,3,4]转换为SQL Server 2012中6位字符串格式的100110?

示例

string  [2,4,5] 

应转换为

string 001011

我必须使6位数字符串,并且字符串000000中的数字或位置应转换为1,假设在上面的字符串[2,4,5]中表示000000的第2,第4和第5指数应转换为1 。最终字符串应为001011

enter image description here

2 个答案:

答案 0 :(得分:3)

您可以尝试从PARSENAME()

开始SQL Server 2012功能
DECLARE @DATA1 VARCHAR(6) = '000000'

SELECT      A.DATA [Original String],
            STUFF(STUFF(STUFF(@DATA1, [First]+1, 1, '1'), [Second]+1 , 1, '1'), [Third]+1, 1, '1') [Converted String] FROM 
(
    SELECT DATA, PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),3) [First], PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),2) [Second], PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),1) [Third] FROM <table_name>
) A

结果:

 Original String    Converted String
 [0, 3, 4]          100110
 [1, 3, 4]          010110

您可以了解Parsename()功能.. https://docs.microsoft.com/en-us/sql/t-sql/functions/parsename-transact-sql

答案 1 :(得分:2)

DECLARE @zero_str VARCHAR(6) = '000000'
-- Generate table alike to yours    
DECLARE @yourTable TABLE (
    [value] varchar(max)
)

INSERT INTO @yourTable VALUES ('[2,4,5]'),('[0,3,4]' )
-- convert array to xml
;WITH cte AS (
    SELECT  [value],
            CAST('<a>'+REPLACE(SUBSTRING([value],2,LEN([value]) - 2),',','</a><a>')+'</a>' as xml) as x
    FROM @yourTable
)
-- do the stuff
SELECT  c.[value],
        RIGHT(@zero_str + CAST(SUM(CAST(STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') as int)) as varchar(6)),6 )
FROM cte c
CROSS APPLY x.nodes('/a') as t(c)
GROUP BY c.[value]

输出:

value   (No column name)
[0,3,4] 100110
[2,4,5] 001011

说明:

STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1')这会将000000的某些部分更改为1,在此部分后我们会:

[2,4,5] 001000
[2,4,5] 000010
[2,4,5] 000001
[0,3,4] 100000
[0,3,4] 000100
[0,3,4] 000010

在表格中。然后我们对int进行CASTing?所以我们可以使用SUM,之后这些数据就像:

[0,3,4] 100110
[2,4,5] 1011

然后我们添加000000字符串并使用RIGHT只获得6个符号。

希望有所帮助!

注意:

如果表中没有id,则在CTE部分使用ROW_NUMBER。

DECLARE @zero_str VARCHAR(6) = '000000'
-- Generate table alike to yours    
DECLARE @yourTable TABLE (
    [value] varchar(max)
)

INSERT INTO @yourTable VALUES ('[2,4,5]'),('[0,3,4]'),('[2,3,4]'),('[2,4,5]'),('[0,3,4]'),('[2,3,4]')
-- convert array to xml
;WITH cte AS (
    SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as rn,
            [value],
            CAST('<a>'+REPLACE(SUBSTRING([value],2,LEN([value]) - 2),',','</a><a>')+'</a>' as xml) as x
    FROM @yourTable
)
-- do the stuff
SELECT  c.rn,
        c.[value],
        RIGHT(@zero_str + CAST(SUM(CAST(STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') as int)) as varchar(6)),6 )
FROM cte c
CROSS APPLY x.nodes('/a') as t(c)
GROUP BY c.rn, c.[value]

输出:

rn  value   (No column name)
2   [0,3,4] 100110
5   [0,3,4] 100110
3   [2,3,4] 001110
6   [2,3,4] 001110
1   [2,4,5] 001011
4   [2,4,5] 001011