2

I want to script query to validate if not have existing column test to add it after check condition. But in those two ways it is not working.

Way 1:

IF [dbo].[TEST].TEST NOT EXISTS
BEGIN
 ALTER TABLE [dbo].[TEST] ADD TEST INT;

Way 2:

ALTER TABLE [dbo].[TEST] ADD TEST INT
where NOT EXISTS in ([dbo].[TEST].TEST);
4
  • You want to check if the table exists or if any rows exist in the table? Mar 23 at 11:08
  • @Charlieface I want to check if the row exist and if it's not exist to add it in the table.
    – Ceci A.
    Mar 23 at 11:12
  • You are adding a column not a row though? Mar 23 at 11:13
  • @Charlieface Yes, my mistake it's a column.
    – Ceci A.
    Mar 23 at 11:14

1 Answer 1

5

If you want to script conditional addition of a column (only if it does not already exist in the table), you can use the sys.columns system catalogue in this way:

IF NOT EXISTS
(
  SELECT
    *
  FROM
    sys.columns
  WHERE
    object_id = OBJECT_ID('dbo.TEST')
    AND name = 'TEST'
)
  ALTER TABLE
    dbo.TEST
  ADD
    TEST int NULL
;
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.