在 MySQL 中,我可以这样做:
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;
其输出为:
num
1
2
3
4
5
6
7
8
我尝试在 sql server 中执行此操作,但遇到了许多障碍:
首先我尝试了这个:
SELECT * FROM
(select 0 union all select 1) t1,
(select 0 union all select 1) t2,
(select 0 union all select 1) t3;
并收到:
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'.
所以我这样做了:
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;
- 为什么我必须为派生表的第 1 列指定名称?
接下来,我尝试设置一个标量,我猜我必须这样做:
DECLARE @row as int
SET @row = 0
我可以做这个:
SELECT @row = @row + 1
在我这样做之前没有任何结果SELECT @row
,现在显示了1
我不能这样做(因为我一开始在 MySQL 中):
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;
我得到:
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'.
- 如何模仿 sql server 中第一个查询(来自 MySQL)的行为?