how can I tell if a colomn exists or not?

  • I'd like to use the following sql in a stored procedure, but I need to find out if the colomn exists or not, can anyone help?

    SET @sql = 'ALTER TABLE [programversion]  ADD [' + @col +'] varchar (200)'

    exec (@sql)

  • information_schema views are the most correct way to do it;

    IF EXISTS(select * from information_schema.columns where tablename='programversion' and columnname=@col )

    BEGIN

    SET @sql = 'ALTER TABLE [programversion]  ADD [' + @col +'] varchar (200)'

    exec (@sql)

    END

    this works too

    select * from syscolumns where object_id(id) = '' and name=''

    IF EXISTS(select * from syscolumns where object_id(id) = 'programversion' and name=@col )

    BEGIN

    SET @sql = 'ALTER TABLE [programversion]  ADD [' + @col +'] varchar (200)'

    exec (@sql)

    END

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Didn't you mean

    IF NOT EXISTS(select * from information_schema.columns where tablename='programversion' and columnname=@col )

    Far away is close at hand in the images of elsewhere.
    Anon.

  • many thanks Lowell, especially for the quick reply

  • That's true, but what's a 'NOT' between friends

  • Thanks David

  • I've just added your code to my Stored Procedure and when I do a Check syntax I get the following error message

    invalid colomn name 'tablename'

    invalid colomn name 'colomnname'

     

  • Mick

    Books Online tells you the names of the columns.  They're TABLE_NAME and COLUMN_NAME.

    John

  • that's what i get for rushing out an answer;

    David Burrows, as usual, is correct.

    NOT Exists...

    the fields are TABLE_NAME and COLUMN_NAMe...with underscores;

    select * from information_schema.columns where table_name='' and column_name=''

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Thanks lads, it all works now thanks to you

Viewing 10 posts - 1 through 9 (of 9 total)

You must be logged in to reply to this topic. Login to reply