开发者

Can't fetch into varchar with t sql

I'm trying to fetch the ID and a serial number from a table in a cursor. As a test, I've written the following T-SQL

DECLARE @sensId 开发者_StackOverflowAS int
DECLARE @serNo as varchar

DECLARE Sensor_Cursor CURSOR FOR
    SELECT  id, serNo
    FROM    sensor
    WHERE   serNo in ('000000002C507650', '0000000038507650', '0000000034507650', '0000000070507650', '0000000044507850', '00000000843060B0');
OPEN Sensor_Cursor;
FETCH NEXT FROM Sensor_Cursor
    INTO @sensId, @serNo;
WHILE @@FETCH_STATUS = 0
   BEGIN
    SELECT @sensId, @serNo
    FETCH NEXT FROM Sensor_Cursor
        INTO @sensId, @serNo;
   END;
CLOSE Sensor_Cursor;
DEALLOCATE Sensor_Cursor;

It returns:

59     0
60     0
61     0
62     0

Why the zeroes? What am I missing?

The query:

SELECT  id, serNo
FROM    sensor
WHERE   serNo in ('000000002C507650', '0000000038507650', '0000000034507650', '0000000070507650', '0000000044507850', '00000000843060B0');

returns

id  serNo
59  000000002C507650
60  0000000038507650
61  0000000034507650
62  0000000070507650


I suspect

DECLARE @serNo as varchar

is defaulting to a length of 1, i.e. varchar(1). Instead, declare it as such:

DECLARE @serNo as varchar(20)

or whatever maximum length it needs to support.


Declare the varchar @serNo variable with an appropriate length, like

DECLARE @serNo as varchar(20)


You need to define the length of your varchar variable. The default is 1 character.

ALso cursors are generally a bad thing, it would be better if you can use some sort of set-based processing espciallly if you have lots of records. This might help you to see if there is a better way to do what you want: http://wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜