从逗号分隔的INT字符串创建临时表

时间:2014-01-03 18:49:01

标签: mysql sql database comma table-variable

我想在这里使用临时表和WHILE子句分享我的发现。我将逗号分隔的INT字符串分开,以便在IN语句中使用。

1 个答案:

答案 0 :(得分:-1)

DECLARE @fk_ArtworkType_ID varchar(20) = '1, 2, 13' 
SET @fk_ArtworkType_ID = REPLACE(@fk_ArtworkType_ID, ' ', '')

DECLARE @ArtworkTypeIDTable TABLE (fk_ArtworkType_ID int)
DECLARE @Count AS INT = 0
SET @Count = LEN(@fk_ArtworkType_ID) - LEN(REPLACE(@fk_ArtworkType_ID, ',', '')) + 1
WHILE @Count > 0
BEGIN
    IF @Count <> 1
        BEGIN 
            INSERT INTO @ArtworkTypeIDTable VALUES(SUBSTRING(@fk_ArtworkType_ID, 0, CHARINDEX(',', @fk_ArtworkType_ID, 0)))
            SET @fk_ArtworkType_ID = SUBSTRING(@fk_ArtworkType_ID, (CHARINDEX(',', @fk_ArtworkType_ID, 0) + 1), LEN(@fk_ArtworkType_ID))
        END
    ELSE
        BEGIN 
            INSERT INTO @ArtworkTypeIDTable VALUES(@fk_ArtworkType_ID)
        END
    SET @Count = @Count - 1
END;