Skip to main content
deleted 132 characters in body
Source Link
Aaron Bertrand
  • 181.5k
  • 28
  • 402
  • 619
added 109 characters in body
Source Link
Aaron Bertrand
  • 181.5k
  • 28
  • 402
  • 619

As for the overall requirement of repeating this query against all date columns in the database, here is how I would do it (I confess I did not even lookI've looked at the SO question you reference, and it just shows how to do this for one table):

As for the overall requirement, here is how I would do it (I confess I did not even look at the SO question):

As for the overall requirement of repeating this query against all date columns in the database, here is how I would do it (I've looked at the SO question you reference, and it just shows how to do this for one table):

added 886 characters in body
Source Link
Aaron Bertrand
  • 181.5k
  • 28
  • 402
  • 619

You should try printing your commandcommands when they yield errors. If you issued this instead of executing it:

Which isn't even a valid BETWEENBETWEEN operation, even if it could translate those to dates.

As for the overall requirement, here is how I would do it (I confess I did not even look at the SO question):

DECLARE @b DATE = '2012-07-01', @e DATE = '2014-01-25', 
        @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'
DELETE ' + QUOTENAME(s.name) 
 + '.' + QUOTENAME(t.name) + '
  WHERE ' + QUOTENAME(c.name) + ' >= @b
  AND ' + QUOTENAME(c.name) + ' < DATEADD(DAY, 1, @e);'
 FROM sys.tables AS t
 INNER JOIN sys.schemas AS s
 ON t.[schema_id] = s.[schema_id]
 INNER JOIN sys.columns AS c
 ON t.[object_id] = c.[object_id]
 WHERE c.system_type_id IN (40,42,43,58,61);
       -- or just = 40 if you're only interested in DATE columns

PRINT @sql;
-- EXEC sp_executesql @sql, N'@b DATE, @e DATE', @b, @e;

You should try printing your commands when they yield errors. If you issued this instead of executing it:

Which isn't even a valid BETWEEN operation, even if it could translate those to dates.

As for the overall requirement, here is how I would do it (I confess I did not even look at the SO question):

DECLARE @b DATE = '2012-07-01', @e DATE = '2014-01-25', 
        @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'
DELETE ' + QUOTENAME(s.name) 
 + '.' + QUOTENAME(t.name) + '
  WHERE ' + QUOTENAME(c.name) + ' >= @b
  AND ' + QUOTENAME(c.name) + ' < DATEADD(DAY, 1, @e);'
 FROM sys.tables AS t
 INNER JOIN sys.schemas AS s
 ON t.[schema_id] = s.[schema_id]
 INNER JOIN sys.columns AS c
 ON t.[object_id] = c.[object_id]
 WHERE c.system_type_id IN (40,42,43,58,61);
       -- or just = 40 if you're only interested in DATE columns

PRINT @sql;
-- EXEC sp_executesql @sql, N'@b DATE, @e DATE', @b, @e;
Source Link
Aaron Bertrand
  • 181.5k
  • 28
  • 402
  • 619
Loading