1

I want to delete a specific attribute from each and every table in the database. For an example: I want to delete CustomerID (column name) with a value of '2' from each and every table in the database

I am trying to delete records where there is a customer field and it has a value of 2 but I get an error that says there is incorrect syntax near keyword delete

declare @SearchTerm nvarchar(4000) 
declare @ColumnName sysname

set @SearchTerm = N'2' -- Term to be searched for
set @ColumnName = N'customerID' --**column**

 set nocount on

 declare @TabCols table (
      id int not null primary key identity
      , table_schema sysname not null
      , table_name sysname not null
      , column_name sysname not null
      , data_type sysname not null
  )

insert into @TabCols (table_schema, table_name, column_name, data_type)
    select 
        t.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE
    from INFORMATION_SCHEMA.TABLES t
    join INFORMATION_SCHEMA.COLUMNS c on t.TABLE_SCHEMA = c.TABLE_SCHEMA
                                      and t.TABLE_NAME = c.TABLE_NAME
    where 1 = 1
      and t.TABLE_TYPE = 'base table'
      and c.DATA_TYPE not in ('image', 'sql_variant')
      and c.COLUMN_NAME like case when len(@ColumnName) > 0 then @ColumnName else '%' end
    order by c.TABLE_NAME, c.ORDINAL_POSITION

declare
  @table_schema sysname
, @table_name sysname
, @column_name sysname
, @data_type sysname
, @exists nvarchar(4000) -- Can be max for SQL2005+
, @sql nvarchar(4000) -- Can be max for SQL2005+
, @where nvarchar(4000) -- Can be max for SQL2005+
, @run nvarchar(4000) -- Can be max for SQL2005+


while exists (select null from @TabCols) begin

select top 1
      @table_schema = table_schema
    , @table_name = table_name
   -- , @exists = 'select null from [' + table_schema + '].[' +    table_name + '] where 1 = 0'
    , @sql = 'delete''' + '[' + table_schema + '].[' + table_name + ']' + ''' as TABLE_NAME, from [' + table_schema + '].[' + table_name + '] where 1 = 0'
    , @where = ''
from @TabCols
order by id

while exists (select null from @TabCols where table_schema = @table_schema and table_name = @table_name) begin

    select top 1
          @column_name = column_name
        , @data_type = data_type
    from @TabCols
    where table_schema = @table_schema
        and table_name = @table_name
    order by id

    -- Special case for money
    if @data_type in ('money', 'smallmoney') begin
        if isnumeric(@SearchTerm) = 1 begin
            set @where = @where + ' or [' + @column_name + '] = cast(''' + @SearchTerm + ''' as ' + @data_type + ')' -- could also cast the column as varchar for wildcards
        end
    end
    -- Special case for xml
    else if @data_type = 'xml' begin
        set @where = @where + ' or cast([' + @column_name + '] as nvarchar(max)) like ''' + @SearchTerm + ''''
    end
    -- Special case for date
    else if @data_type in ('date', 'datetime', 'datetime2', 'datetimeoffset', 'smalldatetime', 'time') begin
        set @where = @where + ' or convert(nvarchar(50), [' + @column_name + '], 121) like ''' + @SearchTerm + ''''
    end
    -- Search all other types
    else begin
        set @where = @where + ' or [' + @column_name + '] like ''' + @SearchTerm + ''''
    end

    delete from @TabCols where table_schema = @table_schema and table_name = @table_name and column_name = @column_name

end

set @run = 'if exists(' + @exists + @where + ') begin ' + @sql + @where + ' print ''' + @table_name + ''' end'
print @run
exec sp_executesql @run

end

 set nocount off
7
  • What is your question? Commented Oct 6, 2015 at 16:27
  • Why won't it delete the values I set from all tables in the database? Commented Oct 6, 2015 at 16:28
  • 1
    You should be using sys.tables and sys.columns instead of the legacy INFORMATION_SCHEMA views. sqlblog.org/2011/11/03/… Commented Oct 6, 2015 at 16:28
  • Are you trying to update column values or delete the rows? You certainly don't need a loop here. And how can you not know what datatype you are looking for? Are you suggesting that CustomerID changes datatypes in every table? Commented Oct 6, 2015 at 16:30
  • 1
    Forget the code. Your stated objective is not clear. Are you looking delete records where there is a customerId field and it has a value of 2? If you want to do something else, specify what it is as clearly as you can. Commented Oct 6, 2015 at 16:31

2 Answers 2

1

Here is another method based on the example posted by ewahner. The big difference is this doesn't use a cursor because you really don't need one for this.

declare @columnName nvarchar(255)
declare @intValue int
set @columnName = 'CustomerId'
set @intValue = 1
declare @DeleteValue varchar(10)
set @DeleteValue = convert(varchar(10), @intValue)

declare @sql nvarchar(max) = ''

select @sql =  @sql + 'delete ' + object_name(c.object_id) + ' where ' + @columnName + ' = ' + @DeleteValue + ';'
from sys.columns c 
where c.name = @columnName

select @sql

/* Uncomment the line below in order to run */
--exec sp_executesql @sql
Sign up to request clarification or add additional context in comments.

12 Comments

when I use this code. It prints a message that the row is deleted but its not deleted in the tables
What do you mean it prints a message? Do you mean you see the delete statements but if you look in the table it is still there?
Do you see the part at the bottom? The comment that says UNCOMMENT THE LINE BELOW??? It is commented out until you are satisfied it will do what you want.
yep I did that and recieved and error that said. Could not find stored procedure.........
error message: "Could not find stored procedure 'delete customer where CustomerId = 2;delete Orders where CustomerId = 2;'."
|
0

Use at your own risk. You will need to uncomment the exec line. But first run it without uncommenting to make sure it gets the tables you want.

declare @columnName nvarchar(255)
declare @intValue int
set @columnName = 'CustomerId'
set @intValue = 1
declare curs cursor for 
    select object_name(c.object_id) as tableName
      from sys.columns c 
     where c.name = @columnName

declare @tableName nvarchar(255)
open curs
fetch next from curs into @tableName
while @@fetch_status = 0
begin

    declare @sql nvarchar(1000)

    set @sql = 'delete ' + @tableName + ' where ' + @columnName + '=' + convert(varchar(10), @intValue)

    print @sql
    /* Uncomment the line below in order to run */
    --exec sp_executesql @sql
    fetch next from curs into @tableName
end
close curs
deallocate curs

2 Comments

it tells me it can not find stored procedure
There are no stored procedures. This is just a script. You can put a use your_database_name and a go and then execute this script.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.