将SQL Server列中的二进制字符串拆分为单独列中的各个位

时间:2017-09-15 03:40:34

标签: sql-server split

我有几列8位字符串(例如'01001000')。我想将每列中的字符串分成8列,每列一列。

有没有比复制和粘贴substring(str, n, 1)更清洁的方式了?

注意我随后将按另一列进行分组,并计算每个单独位位置的1的数量....以防有助于理解。

2 个答案:

答案 0 :(得分:1)

我认为这可能有所帮助:

CREATE TABLE tab123(B1 INT, B2 INT, B3 INT, B4 INT, B5 INT, B6 INT, B7 INT, B8 INT)

DECLARE @TAB VARCHAR(100) = '01001000',
     @VALUES VARCHAR(MAX) = 'INSERT INTO TAB123 SELECT '

SELECT @VALUES = @VALUES + VAL
   FROM
      (
         SELECT SUBSTRING(@TAB, NUMBER, 1) + ',' VAL
             FROM master.dbo.spt_values
             WHERE TYPE = 'P' AND NUMBER BETWEEN 1 AND LEN(@TAB)
      ) AS A

SELECT @VALUES = SUBSTRING(@VALUES, 1, LEN(@VALUES) - 1)

EXEC (@VALUES)

SELECT * FROM tab123

DROP TABLE tab123

答案 1 :(得分:0)

创建一个包含8位列的新表,然后从当前表中对此新表执行INSERT INTO ... SELECT

INSERT INTO newTable (b1, b2, b3, b4, b5, b6, b7, b8)
SELECT
    CAST(SUBSTRING(col, 1, 1) AS BIT),
    CAST(SUBSTRING(col, 2, 1) AS BIT),
    CAST(SUBSTRING(col, 3, 1) AS BIT),
    CAST(SUBSTRING(col, 4, 1) AS BIT),
    CAST(SUBSTRING(col, 5, 1) AS BIT),
    CAST(SUBSTRING(col, 6, 1) AS BIT),
    CAST(SUBSTRING(col, 7, 1) AS BIT),
    CAST(SUBSTRING(col, 8, 1) AS BIT)
FROM oldTable