SQLFiddle: must declare the scalar variable error
Asked Answered
L

3

7

I'm trying to execute next SQL statement (SQL Server 2008 Profile)

DECLARE @fun int;
SET @fun = 40;

select cast(@fun as varchar(10)) + 'hello'

and SQLFiddle gives me the error: Must declare the scalar variable @fun

Where I'm wrong?

enter image description here

http://sqlfiddle.com/#!3/d41d8/42156

Latecomer answered 7/1, 2015 at 18:38 Comment(0)
N
3

I think the semicolons are introducing the problem here.

As described here: http://www.sql-server-helper.com/error-messages/msg-137.aspx and here: SQL Server - Variable declared but still says "Must declare the scalar variable", the problem arises when the statements are executed individually instead of as a “unit”, and the semicolons seem to trigger that.

When I remove the semicolons from your statement, it works: http://sqlfiddle.com/#!3/d41d8/42159

Nudi answered 7/1, 2015 at 18:46 Comment(1)
While this works in this simple case, it is not exactly a best practice, and will break when the OP uses a query construct that actually requires semi-colons.Procreant
S
10

You need to select the [Go] from last dropdown.

enter image description here

Sowell answered 7/1, 2015 at 18:52 Comment(0)
N
3

I think the semicolons are introducing the problem here.

As described here: http://www.sql-server-helper.com/error-messages/msg-137.aspx and here: SQL Server - Variable declared but still says "Must declare the scalar variable", the problem arises when the statements are executed individually instead of as a “unit”, and the semicolons seem to trigger that.

When I remove the semicolons from your statement, it works: http://sqlfiddle.com/#!3/d41d8/42159

Nudi answered 7/1, 2015 at 18:46 Comment(1)
While this works in this simple case, it is not exactly a best practice, and will break when the OP uses a query construct that actually requires semi-colons.Procreant
U
0

You dont have to remove the semicolons, the important part is select [GO] as query terminator on the bottom right conner dropdown.

FIDDLE DEMO

DECLARE @fun int;
SET @fun = 40;
select @fun;
GO

select 10;
GO

select @fun + 10;

The first three sentences are executed as a whole because now ; doesnt end the query. So @fun is visible on that scope.

Second block take notice you need leave a space after GO.

Third block wont work because @fun isn't define in this block.

Underarm answered 17/7, 2015 at 21:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.