3

我正在尝试增加这样的变量的 nvarchar 值;

    declare @i int
    set @i = 0
    -- I want a book `@BookSerialNo`  to be increment like e.g abcde-1, abcde-2 
    set @BookSerialNo = CAST(@BookSerialNo +'-' + @i as nvarchar(50));
    WHILE(@i<>@Quantity)
        BEGIN
            INSERT INTO Library.BookDetail
            (
                BookId,
                BookSerialNo,
                CreatedBy,
                CreateDate,
                UpdateDate,
                Updateby
            )
            VALUES
            (
                @BookId,
                @BookSerialNo,
                @CreatedBy,
                @CreatedDate,
                @UpdatedDate,
                @UpdatedBy
            )
            SET @i = @i+1;
        END

所以,我的问题是,
如何@BookSerialNo在循环中增加每个时间的值?
我想要它,例如'abcdef-1','abcdef-2','abcdef-3',我只想在'-'之后包含数字。

4

3 回答 3

7

试试这个..

    set @BookSerialNo = @BookSerialNo +'-0';
    WHILE(@i<>@Quantity)
        BEGIN
            INSERT INTO Library.BookDetail
            (
                BookId,
                BookSerialNo,
                CreatedBy,
                CreateDate,
                UpdateDate,
                Updateby
            )
            VALUES
            (
                @BookId,
                @BookSerialNo,
                @CreatedBy,
                @CreatedDate,
                @UpdatedDate,
                @UpdatedBy
            )
            SET @i = @i+1;
            --increment the serialno also
            SET @BookSerialNo = SUBSTRING(@BookSerialNo, 0, CHARINDEX('-',@BookSerialNo)+1);  
            set @BookSerialNo = @BookSerialNo + CAST (@i as nvarchar(50));
        END
于 2013-03-19T06:58:17.263 回答
2

只是移动set里面while

WHILE(@i<>@Quantity)
    BEGIN
    set @BookSerialNo = cast(@BookSerialNo as nvarchar(50)) +'-' + 
                        cast(@i as nvarchar(50));
    ....
    SET @i = @i+1;
    END
于 2013-03-19T06:43:37.237 回答
0

假设 @BookSerialNo 数据类型是 nvarchar

Try this

WHILE(@i<>@Quantity)
BEGIN
    set @BookSerialNo = @BookSerialNo +'-' + CONVERT(NVARCHAR(50),@i);
    ....
    SET @i = @i+1;
END
于 2013-03-19T06:56:03.097 回答