SQL Server 2000 TOP and OUTPUT keywords

大兔子大兔子 提交于 2019-12-25 02:35:12

问题


This query works great in SQL Server 2005 and 2008. How would I write it in SQL Server 2000?

UPDATE TOP 10 myTable
SET myBooleanColumn = 1
OUTPUT inserted.*

Is there any way to do it besides running multiple queries?


回答1:


To be honest, your query doesn't really make sense, and I have a hard time understanding your criteria for "great." Sure, it updates 10 rows, and doesn't give an error. But do you really not care which 10 rows it updates? Your current TOP without ORDER BY suggests that you want SQL Server to decide which rows to update (and that's exactly what it will do).

To accomplish this in SQL Server 2000 (without using a trigger), I think you would want to do something like this:

SET NOCOUNT ON;

SELECT TOP 10 key_column
INTO #foo
FROM dbo.myTable
ORDER BY some_logical_ordering_clause;

UPDATE dbo.MyTable
SET myBooleanColumn = 1
FROM #foo AS f
WHERE f.key_column = dbo.MyTable.key_column;

SELECT * FROM dbo.MyTable AS t
INNER JOIN #foo AS f
ON t.key_column = f.key_column;

If you want a simple query, then you can have this trigger:

CREATE TRIGGER dbo.upd_tr_myTable
ON dbo.myTable
FOR UPDATE
AS
BEGIN
  SET NOCOUNT ON;

  SELECT * FROM inserted;
END
GO

Note that this trigger can't tell if you're doing your TOP 10 update or something else, so all users will get this resultset when they perform an update. Even if you filter on IF UPDATE(myBooleanColumn), other users may still update that column.

In any case, you'll still want to fix your update statement so that you know which rows you're updating. (You may even consider a WHERE clause.)



来源:https://stackoverflow.com/questions/10338811/sql-server-2000-top-and-output-keywords

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!