Click here to Skip to main content
15,887,923 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
for example i will check if i have a
Table: Week
Columns: Monday, Tuesday, Wednesday ,Thursday

but i want to check if friday exist

SQL
IF NOT EXISTS(SELECT Friday FROM INFORMATION_SCHEMA.COLUMNS)
 ALTER TABLE TimeTB ADD Friday nvarchar(50) DEFAULT 'Free' NOT NULL



Error: Invalid column name 'Friday'.
Posted
Comments
R. Giskard Reventlov 3-Mar-11 13:54pm    
If you have a table that stores data for each day of the week why would you not have a Friday column? Just asking.
royneilfranco 3-Mar-11 14:03pm    
My point here is, I want to add a column if doesn't it exist.

ADD Column then column name :)

SQL
ALTER TABLE Table_Name ADD COLUMN Col_Name nvarchar(50)
 
Share this answer
 
v2
Comments
royneilfranco 3-Mar-11 14:14pm    
The problem is in IF NOT EXISTS(SELECT Friday FROM INFORMATION_SCHEMA.COLUMNS), since Friday doesn't exist, this will pop up Error: Invalid column name 'Friday'.
Ok, strange requirement. Yet, you can use TRY-CATCH in SQL for it.

Try something like:
SQL
BEGIN TRY
  SELECT
     MyNewColumnNameToAddIfNotExists
  FROM
     MyExistingTable
END TRY
BEGIN CATCH
  ALTER TABLE MyExistingTable ADD MyNewColumnNameToAddIfNotExists nvarchar(50) DEFAULT 'Free' NOT NULL      
END CATCH

P.S.: You might need to make sure that the error is because of missing column only!

Further, if needed you can try Transactions along with Try-Catch. Look for details here[^].
 
Share this answer
 
v2
Comments
royneilfranco 3-Mar-11 14:21pm    
Still not working invalid column names still appears
Sandeep Mewara 3-Mar-11 14:24pm    
1. What error? What does it mean - "invalid column names still apear?"
2. I gave you an idea/headsup/way to achieve. Don't just copy-paste and ask me to fix all, please!
3. Did you read the link I gave?
Try!
royneilfranco 3-Mar-11 14:28pm    
Invalid column name 'Friday'. I think Try-Catch process have the same logic as my code
Your SELECT statement is incorrect. Try this:
SQL
IF NOT EXISTS
    (
        SELECT 0 FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'TimeTB' AND COLUMN_NAME = 'Friday'
    )
BEGIN
    ALTER TABLE TimeTB ADD COLUMN [Friday] nvarchar(50) DEFAULT 'Free' NOT NULL
END

Also, I put square brackets around "Friday" just in case it's a reserved word. Looks like somebody already added a similar answer, but it was deleted. Not sure why that is.
 
Share this answer
 
Try this
SQL
IF COLUMNPROPERTY( OBJECT_ID('Week'), 'Friday', 'ColumnId' ) IS NULL
   BEGIN
   ALTER TABLE [Week] ADD [Friday] nvarchar(50) DEFAULT 'Free' NOT NULL
   END
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900