Order by at cursor
5 answers
Like:
DECLARE cur CURSOR FOR
(
SELECT * FROM
(
SELECT TOP 9999999999 -- Necessary...
col_1
,...
,col_n
FROM TABLE_XY
ORDER BY WHATEVER
) AS TempTableBecauseSqlServerSucks
)
Real world example:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_DELDATA_Delete_NON_SOFT_ByForeignKeyDependency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_DELDATA_Delete_NON_SOFT_ByForeignKeyDependency]
GO
-- =============================================
-- Author: Stefan Steiger
-- Create date: 22.06.2012
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[sp_DELDATA_Delete_NON_SOFT_ByForeignKeyDependency]
AS
BEGIN
DECLARE @ThisCmd varchar(500)
DECLARE cur CURSOR
FOR
(
SELECT * FROM
(
SELECT TOP 9999999999
-- Lvl
--,TableName
--,
'DELETE FROM [' + TableName + '] WHERE [' +
(
SELECT
INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE INFORMATION_SCHEMA.COLUMNS.TABLE_NAME = V_DELDATA_Tables_All.TableName
AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME LIKE '%Status'
) + '] = 99; ' AS cmd
FROM V_DELDATA_Tables_All
WHERE (1=1)
AND TableName LIKE 'T_%'
AND TableName NOT LIKE 'T_Ref_%'
AND TableName NOT LIKE 'T_RPT_%'
AND TableName NOT LIKE 'T_Import_%'
AND TableName NOT LIKE 'T_Export_%'
ORDER BY Lvl DESC, TableName ASC
) AS SqlServerSucks
) --End For
OPEN cur
FETCH NEXT FROM cur INTO @ThisCmd
WHILE @@fetch_status = 0
BEGIN
PRINT @ThisCmd
--EXECUTE(@ThisCmd)
FETCH NEXT FROM cur INTO @ThisCmd
END
CLOSE cur
DEALLOCATE cur
END
GO
+4
a source to share
For some reason, the other subquery based answers didn't work for me. It kept dropping rows of SQL Server 2012. In this particular case ~ 100 rows were fetched from the view of some static data crossed with table data.
The cure was to declare the cursor as " forward_only static ":
declare mappingsCursor cursor local forward_only static for
select top 2000000000
a, b, c, d
from MappingsView
order by a, b, c, d;
Ref: Why cursor opened for selection with ORDER does not reflect updates to the following table
Does anyone know the default cursor type when there is an order? Why not always work for "static" data?
+1
a source to share