Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CASE statement to check if column exists in table - SQL Server

I'm using a SQL server statement embedded in some other C# code; and simply want to check if a column exists in my table.

If the column (ModifiedByUSer here) does exist then I want to return a 1 or a true; if it doesn't then I want to return a 0 or a false (or something similar that can be interpreted in C#).

I've got as far as using a CASE statement like the following:

SELECT cast(case WHEN EXISTS (select ModifiedByUser from Tags)              THEN 0              ELSE 1              END as bit) 

But if the ModifiedByUser doesn't exist then I'm getting an invalid column name, instead of the return value.

I've also considered:

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')   BEGIN // Do something here to return a value   END 

But don't know how to conditionally return a value/bool/bit based on the result. Any help much appreciated!

like image 629
WheretheresaWill Avatar asked May 22 '13 08:05

WheretheresaWill


People also ask

How do you check if a column exists in a table in SQL Server?

For checking the existence we need to use the COL_LENGTH() function. COL_LENGTH() function returns the defined length of a column in bytes. This function can be used with the IF ELSE condition to check if the column exists or not.

How do I check if a column is present in SQL?

Colum view to check the existence of column Name in table SampleTable. IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA. COLUMNS WHERE table_name = 'SampleTable' AND column_name = 'Name' ) SELECT 'Column exists in table' AS [Status] ; ELSE SELECT 'Column does not exist in table' AS [Status];


1 Answers

Final answer was a combination of two of the above (I've upvoted both to show my appreciation!):

select case     when exists (       SELECT 1        FROM Sys.columns c        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')           AND c.name = 'ModifiedByUserId'    )     then 1     else 0  end 
like image 122
WheretheresaWill Avatar answered Sep 24 '22 15:09

WheretheresaWill