1

I am getting the error

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '@PacketCode'.

when I try to execute. Something is wrong with my WHILE loop but I can't see what. Any suggestions?

DECLARE @PacketCode as varchar(255)
SET @PacketCode = 'ZZZ_Archive_TEST'

DECLARE @Value as varchar(255)
SET @Value = ''

DECLARE @i int
SET @i = 1

SELECT 
    @Value = (SELECT packetcode
              FROM tblScriptReports
              WHERE packetcode = @PacketCode)

WHILE (@PacketCode = @Value) 
BEGIN
    @PacketCode = @PacketCode + ' (' + @i + ')'

    SELECT @Value = (SELECT packetcode
                    FROM tblScriptReports
                    WHERE packetcode = @PacketCode)

    SET @i = @i + 1                   
END

SELECT @PacketCode
3
  • 1
    Is it Mysql or SQL-Server ? please tag it accordingly Commented Jun 6, 2017 at 17:10
  • It is SQL Server Commented Jun 6, 2017 at 17:13
  • What have you tried? Have you checked documentation? Commented out lines until the error goes away and you know what the problem is? Commented Jun 6, 2017 at 17:40

2 Answers 2

4

In TSQL you assign variable values with the SET command.

So instead of this:

@PacketCode = @PacketCode + ' (' + @i + ')'

You must do this:

SET @PacketCode = @PacketCode + ' (' + @i + ')'

Funny that you did this correctly everywhere else in the code.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes this fixed it! Can't believe I missed it.
1

Try to add a SET in front of the @PacketCode in the BEGIN:

DECLARE @PacketCode as varchar(255)
set @PacketCode = 'ZZZ_Archive_TEST'

DECLARE @Value as varchar(255)
set @Value = ''

DECLARE @i int
set @i = 1

SELECT @Value = (SELECT packetcode
             FROM tblScriptReports
             WHERE packetcode = @PacketCode)

WHILE (@PacketCode = @Value) 

BEGIN

SET @PacketCode = @PacketCode + ' (' + @i + ')'

    SELECT @Value = (SELECT packetcode
                    FROM tblScriptReports
                    WHERE packetcode = @PacketCode)

    set @i = @i + 1                   
END

select @PacketCode

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.