June 11, 2009 at 10:21 pm
Hi ,
I want to insert a new column , check while inserting values.
For example : I have a table TBL with 2 columns , but i want to insert 3 columns so i need to write code that checks wether 3rd column is existing or not and then add new cloumn.But not using simple alter table.
But i need code to compare the values (columns ) while passing in insert statement with columns in That Table.If that column doesnot exits it should automatically add that column.
And i need this code in Dynamic TSQL
June 11, 2009 at 10:42 pm
[font="Verdana"]Wow.
I suspect that you are getting a comma-separated list of values, and you don't know how many columns you will need to store the data until you get the list?
Anyway, you might be better thinking of storing them as related rows, rather than columns. Then you can use a trick similar to the following:
with
ExampleData as (
select '1,2,3' as ListOfValues union all
select '5,6,7,8' as ListOfValues union all
select '9,10' as ListOfValues
)
select*
fromExampleData
cross apply
dbo.fnSplit(ExampleData.ListOfValues, ',')
You can find the code for fnSplit somewhere around on this site. 🙂
[/font]
June 12, 2009 at 1:16 am
I hope this may solve your issue.
IF EXISTS(SELECT * FROM sys.objects WHERE [name] = 'tblTable')
BEGIN
DROP TABLE tblTable
END
CREATE TABLE tblTable (fldID int, fldName varchar(8))
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE 'tblTable' AND COLUMN_NAME LIKE 'fldDesc')
BEGIN
ALTER TABLE tblTable ADD fldDesc varchar(8)
END
INSERT INTO tblTable VALUES (1,'MyName1','MyDesc1')
INSERT INTO tblTable VALUES (2,'MyName2','MyDesc2')
SELECT * FROM tblTable
June 12, 2009 at 6:55 am
He said something about not using ALTER...:-P
Greetz,
Hans Brouwer
June 12, 2009 at 10:22 pm
srikale (6/11/2009)
Hi ,I want to insert a new column , check while inserting values.
For example : I have a table TBL with 2 columns , but i want to insert 3 columns so i need to write code that checks wether 3rd column is existing or not and then add new cloumn.But not using simple alter table.
But i need code to compare the values (columns ) while passing in insert statement with columns in That Table.If that column doesnot exits it should automatically add that column.
And i need this code in Dynamic TSQL
I know it's what you want to do, but it may not be the right thing to do. Perhaps if you told us what you're really trying to accomplish, we could provide a better solution.
--Jeff Moden
Change is inevitable... Change for the better is not.
June 13, 2009 at 3:36 am
srikale (6/11/2009)
But not using simple alter table.
What's the problem with ALTER?
:ermm:
Flo
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply