December 4, 2008 at 7:00 am
Hi All,
I have to add a new column in all the tables which resides in a database.
say for example,
DB Name : Employee
Table Count : 320
Now, I have to add a column called dt_log ( Datatype : Datetime) in all the tables. i.e 320 tables.
will 'DYNAMIC SQL' concept help to do this?
#2:
if the table has index ( clustered or non clustered whatever it may be), the new column should be added in that key.
say for example,
Table Name: emp
Columns:
eno int
ename varchar(25)
dob datetime
age int
salary numeric(8,2)
index name : id01 on (eno,ename,dob)
then dt_log should be modified as below.
i.e
index name : id01 on (eno,ename,dob,dt_log)
how ?
Inputs are welcome!
karthik
December 4, 2008 at 7:03 am
As far as #1 goes, a cursor with the names of all your tables and some dynamic sql should handle it.
For the second part... that sounds dangerous and arbitrary and I don't think I'd do it.
December 4, 2008 at 8:13 am
You could utilize the sp_MSForEachDB if you don't want cursor
but same idea.
sp_MSForEachDB 'ALTER TABLE ? ADD ColumnName ColumnType'
As for second question, it does sound dangerous
but my thinking is cursor for all indexes, and add the column into the index
December 4, 2008 at 8:24 am
I think he'd want: sp_MSForEachTable (And it uses a cursor anyways, but it does save some typing and probably looks a bit cleaner overall)
And with the indexes, you could potentially add it to multiple indexes per table with that approach.
Karthik,
Why does this field need to be added indiscriminately to all these indexes?
December 5, 2008 at 3:21 am
Why does this field need to be added indiscriminately to all these indexes?
This new field should be used in the where clause as a filter.
Say for example,
TableName: Emp
Columns:
Eno int
DOB Datatime
Ename varchar(25)
Salary
Index : id01 on (eno,DOB)
Now,
the new column dt_log has been added.
if i write query like
select eno,DOB,Salary
from emp
where dt_log > '01/01/2008'
it wont use the above index (id01). Am i right ?
Thats why i want to include dt_log column in the existing index.
karthik
December 8, 2008 at 2:11 am
Any inputs ?
karthik
December 9, 2008 at 9:20 am
select eno,DOB,Salary
from emp
where dt_log > '01/01/2008'
The query will not make use of an index on (eno, DOB, dt_log). Try it.
Perhaps you want to add to every table a new index with dt_log as the only column?
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply