如何增加值

时间:2013-09-24 06:46:21

标签: sql-server tsql

我有这样的价值'00100-01999'我需要将此值增加为'00100,00101,...... 01999'

我写了这样的剧本

DECLARE @vc_value VARCHAR(20),
    @min VARCHAR(10),
    @Max VARCHAR(10),
    @String VARCHAR(10),
    @Start BIGINT,
    @End BIGINT
CREATE TABLE #1 (ID VARCHAR(20))
SET @vc_value = '00100-01999'

SET @min = SUBSTRING(@vc_value, 1, CHARINDEX('-', @vc_value) - 1)

SET @Max = SUBSTRING(@vc_value, CHARINDEX('-', @vc_value) + 1, LEN(@vc_value))
SELECT @min,@max

WHILE CAST(@min AS INT) <= CAST(@Max AS INT)
BEGIN

    INSERT INTO #1
    SELECT CAST(@min AS VARCHAR(10))
    SET @min = @min + 1

    SELECT @min
END

SELECT * FROM #1

但我得到的结果为100,101,...... 1999

我需要像'00100,00101,...... 01999'

1 个答案:

答案 0 :(得分:0)

您需要添加所需数量的前导零。试试这个:

WHILE CAST(@min AS INT) <= CAST(@Max AS INT)
BEGIN

    INSERT INTO #1
    SELECT RIGHT('00000'+ CAST(@min AS VARCHAR(10)),5)
    SET @min = @min + 1

    SELECT @min
END

这会将'00000'追加到100,101,.... 1999,将'00000100'作为字符串,然后从该字符串中取出最后5个字符。