Search
 
SCRIPT & CODE EXAMPLE
 

SQL

sql check if column exists

IF COL_LENGTH('<table_name>', '<column_name>') IS NULL
BEGIN
	--column doesnot exists, so, add column here
	ALTER TABLE <table_name> ADD <column_name> BIT NOT NULL DEFAULT(0)
END
Comment

How to check if the column exists in sql table

IF EXISTS(SELECT 1 FROM sys.columns WHERE Name = N'columnName' AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
	ALTER TABLE MyTable ADD COLUMN MyOtherColumn(DATATYPE)
END
Comment

How to check if a column exists in a SQL Server table?


A more concise version

IF COL_LENGTH('table_name','column_name') IS NULL
BEGIN
/* Column does not exist or caller does not have permission to view the object */
END
The point about permissions on viewing metadata applies to all answers not just this one.

Note that the first parameter table name to COL_LENGTH can be in one, two, or three part name format as required.

An example referencing a table in a different database is

COL_LENGTH('AdventureWorks2012.HumanResources.Department','ModifiedDate')
One difference with this answer compared to using the metadata views is that metadata functions such as COL_LENGTH always only return data about committed changes irrespective of the isolation level in effect.
Comment

sql check if column exists

* Using the below query, You can check whether the table1 has a column named "id"

SHOW COLUMNS FROM table1 LIKE 'id'
Comment

PREVIOUS NEXT
Code Example
Sql :: count weekend days between two dates sql 
Sql :: how to update sql server version 
Sql :: sqlite update query python 
Sql :: having in sql server 
Sql :: xampp mysql command to import a large database 
Sql :: sql limit order by 
Sql :: sql exemplos 
Sql :: primary key sql 
Sql :: postgresql delete cascade 
Sql :: mysql extract day from date leading zero 
Sql :: having in sql 
Sql :: how to find sql server installation folder 
Sql :: spark apache sql coalesce 
Sql :: change sql global mode 
Sql :: unique sql 
Sql :: openquery join two tables 
Sql :: switch users mysql 
Sql :: how to replace null values in sql 
Sql :: order of sql 
Sql :: uuid sqlalcomany 
Sql :: mysql pass command from command line 
Sql :: mysql row generator 
Sql :: SQL/delete 
Sql :: how to insert same table data using mysql query 
Sql :: mysql create view 
Sql :: SQL Comments Within Statements 
Sql :: Triggers Syntax 
Sql :: mysql regex select 
Sql :: sql is not like 
Sql :: sql server express 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =