1

在 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. 为什么我必须为派生表的第 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'.
  1. 如何模仿 sql server 中第一个查询(来自 MySQL)的行为?
4

3 回答 3

2

好吧,如果你只想要行号,你可以ROW_NUMBER()在 TSQL 中使用;

SELECT ROW_NUMBER() OVER (ORDER BY t1.f) 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;

这将返回每个组合的行号。ROW_NUMBER()需要一个ORDER BY,所以只需按第一个方便的列排序。

SQLFiddle 在这里

于 2012-10-11T21:04:53.477 回答
1

如果我理解其意图,并且您拥有 SQL Server 2005 或更高版本,请尝试以下操作:

select row_number() over(order by t1.f) 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,
(select 0 as f) as t4;

产量:

num
--------------------
1
2
3
4
5
6
7
8
于 2012-10-11T21:05:22.370 回答
0

好吧,对于这个小查询:

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;

您尝试为变量命名,因此设置和输出是您想要的,这是不可能的。你必须做第一个或最后一个,而不是两者..

DECLARE @row as int
SET @row = 0

SELECT @row = @row + 1 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;

SELECT @row as num
于 2012-10-12T09:24:01.300 回答