In MySQL I can do something like this:
SELECT @row := @row + 1 as num FROM
(select 0 union all select 1) t1,
(select 0 union all select 1) t2,
(select 0 union all select 1) t3,
(select @row := 0) as t4;
The output of which is:
num
1
2
3
4
5
6
7
8
I tried to do this in sql server, but met many road blocks:
First I tried this:
SELECT * FROM
(select 0 union all select 1) t1,
(select 0 union all select 1) t2,
(select 0 union all select 1) t3;
and received:
Msg 8155, Level 16, State 2, Line 7
No column name was specified for column 1 of 't1'.
Msg 8155, Level 16, State 2, Line 8
No column name was specified for column 1 of 't2'.
Msg 8155, Level 16, State 2, Line 9
No column name was specified for column 1 of 't3'.
So I did this:
SELECT * FROM
(select 0 as f union all select 1) t1,
(select 0 as f union all select 1) t2,
(select 0 as f union all select 1) t3;
- Why do I have to specify a name for column 1 on the derived tables?
Next, I tried to setup a scalar, I guessed I had to do it this way:
DECLARE @row as int
SET @row = 0
I can do this:
SELECT @row = @row + 1
Which results in nothing back until I do SELECT @row
which now shows a 1
I cannot do (as I was in MySQL at the start):
DECLARE @row as int
SET @row = 0
SELECT @row = @row + 1 as num FROM
(select 0 as f union all select 1) t1,
(select 0 as f union all select 1) t2,
(select 0 as f union all select 1) t3;
I get:
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'as'.
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near 't1'.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near 't2'.
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near 't3'.
- How do I mimic the behavior of the first query (from MySQL) in sql server?