tsql select语句中的自增子查询

发布于 2024-12-27 19:46:09 字数 160 浏览 0 评论 0原文

我有一个 T-SQL select 语句,我想自动增加其中的一列(数据库中不存在)

select dbo.a, dbo.b, dbo.c, select @d:=1; @increment:=@increment+1 AS d

这可能吗?

I have a T-SQL select statement and I want to auto-increment a column in it (that doesn't exist in the database)

select dbo.a, dbo.b, dbo.c, select @d:=1; @increment:=@increment+1 AS d

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

℉絮湮 2025-01-03 19:46:09

假设您使用 SQL 2005 或更高版本:

SELECT dbo.a, dbo.b, dbo.c, ROW_NUMBER() OVER(ORDER BY GETDATE()) AS d

对从数据库返回的行进行排序。如果您想指定顺序,可以这样做:

SELECT dbo.a, dbo.b, dbo.c, ROW_NUMBER() OVER(ORDER BY dbo.a) AS d

对于 SQL 2000 及更早版本,您需要一个唯一值来排序:

SELECT dbo.a, dbo.b, dbo.c, (SELECT COUNT(*) FROM dbo d2 WHERE d2.a <= dbo.a) AS d
FROM dbo

或者如果您不需要单个 SELECT:

SELECT IDENTITY(int,1,1) ID, dbo.a, dbo.b, dbo.c
INTO #Temp
FROM dbo

SELECT * FROM #Temp

Assuming you're using SQL 2005 or later:

SELECT dbo.a, dbo.b, dbo.c, ROW_NUMBER() OVER(ORDER BY GETDATE()) AS d

to order the rows as they are returned form the DB. If you want to specify an order you can do so:

SELECT dbo.a, dbo.b, dbo.c, ROW_NUMBER() OVER(ORDER BY dbo.a) AS d

For SQL 2000 and earlier you need a unique value to order by:

SELECT dbo.a, dbo.b, dbo.c, (SELECT COUNT(*) FROM dbo d2 WHERE d2.a <= dbo.a) AS d
FROM dbo

or if you don't need a single SELECT:

SELECT IDENTITY(int,1,1) ID, dbo.a, dbo.b, dbo.c
INTO #Temp
FROM dbo

SELECT * FROM #Temp
咆哮 2025-01-03 19:46:09

我认为你可以通过以下方式来实现:

select dbo.a, dbo.b, dbo.c,  ROW_NUMBER() OVER (order by dbo.a) as d from somewhere;

我的答案假设 SQL Server 2005+,我认为 D Stanley 的答案将在 2000 年对你有所帮助。

I think you can pull it off with something like:

select dbo.a, dbo.b, dbo.c,  ROW_NUMBER() OVER (order by dbo.a) as d from somewhere;

My answer assumed SQL Server 2005+, I think D Stanley answer will help you in 2000.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文