Select temp 前 1 table returns 只有第一个字符

Select top 1 from temp table returns only first character

在 T-SQL 代码块中,我正在填充临时 table 并执行 WHILE 循环。在 WHILE 循环中,当我为 varchar 值执行 SELECT TOP 1 时,它 returns 只有第一个字符。

这是代码

BEGIN
    DECLARE @RowCounter int;
    SET @RowCounter = 0;

    DECLARE @TotalRows int;  
    SET @TotalRows = 0;

    DECLARE @tempPcsDataId int; 
    SET @tempPcsDataId = 0;

    -- create a temp table
    -- to stack people: PalletLicensePlate in the Db is varchar(50) so I make tempPalletLicensePlate the same
    DECLARE @DistinctPalletsTempTable TABLE 
            (
                 DeliveryDate datetime, 
                 tempPalletLicensePlate varchar(50), 
                 StoreNumber nvarchar(50), 
                 DerivedWmsCode nvarchar(20), 
                 ShipperClid int, 
                 CartonCount int
            );

    -- populate the temp table
    INSERT @DistinctPalletsTempTable 
        SELECT DISTINCT 
            DeliveryDate, PalletLicensePlate, StoreNumber, 
            DerivedWmsCode, ShipperClid, 0
        FROM
            PcsData 
        WHERE
            InsertGuid = '017DA918-3AF3-4F86-949C-C2611E2BEEE8';

    SET @TotalRows = (SELECT COUNT(*) FROM @DistinctPalletsTempTable);

    WHILE @TotalRows >= @RowCounter
    BEGIN
        DECLARE @CartonCountForThisPallet int; 
        SET @CartonCountForThisPallet = 0;

        DECLARE @ThisLicensePlate varchar;  
        SET @ThisLicensePlate = (SELECT TOP 1 tempPalletLicensePlate 
                                 FROM @DistinctPalletsTempTable);

        SELECT @ThisLicensePlate  -- this always returns B  The first character
        SET @CartonCountForThisPallet = (SELECT COUNT(*) 
                                         FROM PcsData 
                                         WHERE PalletLicensePlate = @ThisLicensePlate);

        UPDATE @DistinctPalletsTempTable 
        SET CartonCount = @CartonCountForThisPallet;

        SELECT @RowCounter;
        SELECT @TotalRows;

        SET @RowCounter = @RowCounter + 1;
    END

    SELECT * FROM @DistinctPalletsTempTable;
END

这里是上面代码中select * from @DistinctPalletsTempTable;的图片。可以看到tempPalletLicensePlate是一个长串

如何从第一行获取完整的 tempPalletLicensePlate?

好吧 - 如果您 省略 任何长度规范,一个 SQL 变量声明为 varchar 只是默认为 1 个字符长度 - 这是定义的,well documented behavior:

当数据定义或变量声明语句中没有指定n时,默认长度为1

所以这里并不奇怪,真的......

而且解决方案也非常简单 - 总是在使用 varchar 作为数据类型时显式定义 长度 - 对于变量或参数 ... .

    DECLARE @ThisLicensePlate VARCHAR(50);  -- **DEFINE** then length here!

    SELECT TOP 1 @ThisLicensePlate = tempPalletLicensePlate 
    FROM @DistinctPalletsTempTable;

现在您的 @ThisLicensePlate 将正确显示车牌的 全部 内容!问题真的不是 SELECT TOP 1.... 部分 - 这是你的 SQL 变量

的声明