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 :: mysql Like(searching in the string) 
Sql :: sql auto date 
Sql :: cmd to rename a collumn name in sql 
Sql :: mysql pretty date format 
Sql :: fetch first 5 characters of the string in sql 
Sql :: add user mysql 
Sql :: mysql load data infile csv 
Sql :: sql server: select column values as comma separated string 
Sql :: creer une base de donnée psql 
Sql :: oracle index partition 
Sql :: hotw to alter lengh character vayng postgres 
Sql :: sql get count without group by 
Sql :: mssql how to insert more than 1000 rows 
Sql :: alter database name script 
Sql :: show columns in sql 
Sql :: how select a json value in mysql 
Sql :: oracle list duplicates 
Sql :: mysql list users 
Sql :: postgres set default schema 
Sql :: mysqldump: Got error: 1045: Access denied for user 
Sql :: how to use lower case in mysql 
Sql :: mysql add column 
Sql :: is mysql and sqlite same 
Sql :: truncate table postgres 
Sql :: laravel get sql query eloquent with parameters 
Sql :: select last 2 characters sql 
Sql :: how to connect to xampp sql server on windows cmd 
Sql :: set id count mysql 
Sql :: select if then postgresql 
Sql :: sql create schema 
ADD CONTENT
Topic
Content
Source link
Name
7+1 =