Davy Knuysen

SQL Server, .Net, ...

  Home  |   Contact  |   Syndication    |   Login
  53 Posts | 0 Stories | 19 Comments | 30 Trackbacks

News

Archives

Post Categories

Blogs I read

Yesterday, someone asked me how to alter every table of a database.

The script below declares a cursor, fills it with the list of tables and executes an alter statement while looping thru the cursor.

 

-- Declare a cursor for the list of all the tables in the database
DECLARE ListOfTables CURSOR FOR

SELECT Table_Name
FROM Information_Schema.Tables

OPEN ListOfTables

DECLARE @TableName Varchar(100)
DECLARE @QueryString Varchar(MAX)
DECLARE @Column Varchar(100)

-- Replace the alter statement here:
SET @Column = 'TestKolom3 VARCHAR(20) NOT NULL'

-- Execute alter statement for every table
FETCH NEXT FROM ListOfTables INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN

SET @QueryString = 'ALTER TABLE ' + @TableName + ' ADD ' + @Column
print 'Executing Query : ' + @QueryString
EXEC(@QueryString)

FETCH NEXT FROM ListOfTables INTO @TableName
END

CLOSE ListOfTables
DEALLOCATE ListOfTables

 

Enjoy!

posted on Friday, September 14, 2007 9:17 AM

Feedback

# re: ALTER every TABLE in a database 9/14/2007 11:21 AM David Brabant
You do not need a cursor for doing that. And using information_schema.tables is better.

declare @Tables table ( name varchar(128))

insert @Tables
select Table_Name
from Information_Schema.Tables

while exists(select 1 from @Tables)
begin
select top 1 @TableName = name from @Tables
delete from @Tables where name = @TableName

/* blah - same thing as yours*/
end


# re: ALTER every TABLE in a database 9/16/2007 3:08 AM Eric
David, since you would not being using this type of utility query all the time it really doesn't matter if you use a cursor or table data type. Plus at least Davy's cursor code actually does something useful. Your suggestion will only loop indefinitely.

# re: ALTER every TABLE in a database 9/16/2007 11:29 PM David Brabant
@Eric

No, it won't.


Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 7 and 6 and type the answer here: