If I've been told a table (or proc) name, but not which connected database the object is located in, is there any simple script to search for it? Maybe search somewhere in the System Databases? (I'm using SQL Server 2005)
There is a schema called INFORMATION_SCHEMA schema which contains a set of views on tables from the SYS schema that you can query to get what you want.
A major upside of the INFORMATION_SCHEMA is that the object names are very query friendly and user readable. The downside of the INFORMATION_SCHEMA is that you have to write one query for each type of object.
The Sys schema may seem a little cryptic initially, but it has all the same information (and more) in a single spot.
You'd start with a table called SysObjects (each database has one) that has the names of all objects and their types.
One could search in a database as follows:
Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
and [Name] like '%YourObjectName%'
Now, if you wanted to restrict this to only search for tables and stored procs, you would do
Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
and [Name] like '%YourObjectName%'
and Type in ('U', 'P')
If you look up object types, you will find a whole list for views, triggers, etc.
Now, if you want to search for this in each database, you will have to iterate through the databases. You can do one of the following:
If you want to search through each database without any clauses, then use the sp_MSforeachdb as shown in an answer here.
If you only want to search specific databases, use the "USE DBName" and then search command.
You will benefit greatly from having it parameterized in that case. Note that the name of the database you are searching in will have to be replaced in each query (DatabaseOne, DatabaseTwo...). Check this out:
Declare #ObjectName VarChar (100)
Set #ObjectName = '%Customer%'
Select 'DatabaseOne' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseOne.Sys.Objects
Where 1=1
and [Name] like #ObjectName
and Type in ('U', 'P')
UNION ALL
Select 'DatabaseTwo' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseTwo.Sys.Objects
Where 1=1
and [Name] like #ObjectName
and Type in ('U', 'P')
UNION ALL
Select 'DatabaseThree' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseThree.Sys.Objects
Where 1=1
and [Name] like #ObjectName
and Type in ('U', 'P')
sp_MSforeachdb 'select db_name(), * From ?..sysobjects where xtype in (''U'', ''P'') And name = ''ObjectName'''
Instead of 'ObjectName' insert object you are looking for. First column will display name of database where object is located at.
Easiest way is to hit up the information_schemas...
SELECT *
FROM information_schema.Tables
WHERE [Table_Name]='????'
SELECT *
FROM information_schema.Views
WHERE [Table_Name]='????'
SELECT *
FROM information_schema.Routines
WHERE [Routine_Name]='????'
You can achieve this by using the following query:
EXEC sp_msforeachdb
'IF EXISTS
(
SELECT 1
FROM [?].sys.objects
WHERE name LIKE ''OBJECT_TO_SEARCH''
)
SELECT
''?'' AS DB,
name AS Name,
type_desc AS Type
FROM [?].sys.objects
WHERE name LIKE ''OBJECT_TO_SEARCH'''
Just replace OBJECT_TO_SEARCH with the actual object name you are interested in (or part of it, surrounded with %).
More details here: https://peevsvilen.blog/2019/07/30/search-for-an-object-in-sql-server/
You can use sp_MSforeachdb to search all databases.
declare #RETURN_VALUE int
declare #command1 nvarchar(2000)
set #command1 = "Your command goes here"
exec #RETURN_VALUE = sp_MSforeachdb #command1 = #command1
Raj
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
/**********************************************************************
Naziv procedure : sp_rfv_FIND
Ime i prezime autora: Srdjan Nadrljanski
Datum kreiranja : 13.06.2013.
Namena : Traži sql objekat na celom serveru
Tabele :
Ulazni parametri :
Izlazni parametri :
Datum zadnje izmene :
Opis izmene :
exec sp_rfv_FIND 'TUN',''
**********************************************************************/
CREATE PROCEDURE [dbo].[sp_rfv_FIND] ( #SEARCHSTRING VARCHAR(255),
#notcontain Varchar(255)
)
AS
declare #text varchar(1500),#textinit varchar (1500)
set #textinit=
'USE #sifra
insert into ##temp2
select ''#sifra''as dbName,a.[Object Name],a.[Object Type]
from(
SELECT DISTINCT sysobjects.name AS [Object Name] ,
case
when sysobjects.xtype = ''C'' then ''CHECK constraint''
when sysobjects.xtype = ''D'' then ''Default or DEFAULT constraint''
when sysobjects.xtype = ''F'' then ''Foreign Key''
when sysobjects.xtype = ''FN'' then ''Scalar function''
when sysobjects.xtype = ''P'' then ''Stored Procedure''
when sysobjects.xtype = ''PK'' then ''PRIMARY KEY constraint''
when sysobjects.xtype = ''S'' then ''System table''
when sysobjects.xtype = ''TF'' then ''Function''
when sysobjects.xtype = ''TR'' then ''Trigger''
when sysobjects.xtype = ''U'' then ''User table''
when sysobjects.xtype = ''UQ'' then ''UNIQUE constraint''
when sysobjects.xtype = ''V'' then ''View''
when sysobjects.xtype = ''X'' then ''Extended stored procedure''
end as [Object Type]
FROM sysobjects
WHERE
sysobjects.type in (''C'',''D'',''F'',''FN'',''P'',''K'',''S'',''TF'',''TR'',''U'',''V'',''X'')
AND sysobjects.category = 0
AND CHARINDEX(''#SEARCHSTRING'',sysobjects.name)>0
AND ((CHARINDEX(''#notcontain'',sysobjects.name)=0 or
CHARINDEX(''#notcontain'',sysobjects.name)<>0))
)a'
set #textinit=replace(#textinit,'#SEARCHSTRING',#SEARCHSTRING)
set #textinit=replace(#textinit,'#notcontain',#notcontain)
SELECT name AS dbName,cast(null as varchar(255)) as ObjectName,cast(null as varchar(255)) as ObjectType
into ##temp1
from master.dbo.sysdatabases order by name
SELECT * INTO ##temp2 FROM ##temp1 WHERE 1 = 0
declare #sifra VARCHAR(255),#suma int,#brojac int
set #suma=(select count(dbName) from ##temp1)
DECLARE c_k CURSOR LOCAL FAST_FORWARD FOR
SELECT dbName FROM ##temp1 ORDER BY dbName DESC
OPEN c_k
FETCH NEXT FROM c_K INTO #sifra
SET #brojac = 1
WHILE (##fetch_status = 0 ) AND (#brojac <= #suma)
BEGIN
set #text=replace(#textinit,'#sifra',#sifra)
exec (#text)
SET #brojac = #brojac +1
DELETE FROM ##temp1 WHERE dbName = #sifra
FETCH NEXT FROM c_k INTO #sifra
END
close c_k
DEALLOCATE c_k
select * from ##temp2
order by dbName,ObjectType
drop table ##temp2
drop table ##temp1
SELECT NAME AS ObjectName
,schema_name(o.schema_id) AS SchemaName, OBJECT_NAME(o.parent_object_id) as TableName
,type
,o.type_desc
FROM sys.objects o
WHERE o.is_ms_shipped = 0
AND o.NAME LIKE '%UniqueID%'
ORDER BY o.NAME
mayby one little change from the top answer, because DB_NAME() returns always content db of execution. so, for me better like below:
sp_MSforeachdb 'select DB_name(db_id(''?'')) as DB, * From ?..sysobjects where xtype in (''U'', ''P'') And name like ''[_]x[_]%'''
In my case I was looking for tables their names started with _x_
Cheers,
Ondrej
----Option 2
SELECT DISTINCT
o.name,
o.xtype
FROM
syscomments c
INNER JOIN
sysobjects o
ON
c.id=o.id
WHERE
c.TEXT LIKE '%TableName%'
order by
o.name desc,
o.xtype desc
select db_name(), * From sysobjects where xtype in ('U', 'P') And name = 'OBJECT_name'
First column will display name of database where object is located at.
Related
Currently I am using:
select *
from sys.tables
where name = 'table name'
But it is taking long time since there are many tables and I have to check each one of them one by one.
You can try using IN like
select * from sys.tables where name IN ('tablename1','tablename2',...)
or you can instead try
SELECT 1
FROM systable INNER JOIN sysuserperm ON systable.creator = sysuserperm.user_id
WHERE sysuserperm.user_name = 'yourusername' AND
systable.table_type = 'BASE' AND
systable.table_name IN ('tablename1', 'tablename2')
GROUP BY sysuserperm.user_name, systable.table_type
Once can use this:
USE DbName
SELECT *
FROM information_schema.tables
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME IN ('tb01','tbl02',...)
If you have a list of table names to check, put it into a table variable and use a code similar to the one below:
declare #t table (
SchemaName sysname not null,
ObjectName sysname not null,
primary key (ObjectName, SchemaName)
);
-- Populate this with your data
insert into #t (SchemaName, ObjectName)
values
(N'dbo', N'SomeTable1'),
(N'dbo', N'AnotherTable2'),
(N'abc', N'DEF');
if exists (
select 0 from #t t
left join INFORMATION_SCHEMA.TABLES xt on xt.TABLE_SCHEMA = t.SchemaName
and xt.TABLE_NAME = t.ObjectName
where xt.TABLE_NAME is null
)
select concat(t.SchemaName, N'.', t.ObjectName) as [MissingObject]
from #t t
left join INFORMATION_SCHEMA.TABLES xt on xt.TABLE_SCHEMA = t.SchemaName
and xt.TABLE_NAME = t.ObjectName
where xt.TABLE_NAME is null;
The aforementioned approach can be easily expanded for multiple kinds of objects. You can replace INFORMATION_SCHEMA.TABLES with sys.all_objects and modify the schema name comparison accordingly.
I need to add a specific column if it does not exist. I have something like the following, but it always returns false:
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName')
How can I check if a column exists in a table of the SQL Server database?
SQL Server 2005 onwards:
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
-- Column Exists
END
Martin Smith's version is shorter:
IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column Exists
END
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.
Tweak the below to suit your specific requirements:
if not exists (select
column_name
from
INFORMATION_SCHEMA.columns
where
table_name = 'MyTable'
and column_name = 'MyColumn')
alter table MyTable add MyColumn int
That should work - take a careful look over your code for stupid mistakes; are you querying INFORMATION_SCHEMA on the same database as your insert is being applied to for example? Do you have a typo in your table/column name in either statement?
Try this...
IF NOT EXISTS(
SELECT TOP 1 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
[TABLE_NAME] = 'Employees'
AND [COLUMN_NAME] = 'EmployeeID')
BEGIN
ALTER TABLE [Employees]
ADD [EmployeeID] INT NULL
END
For the people who are checking the column existence before dropping it.
From SQL Server 2016 you can use new DIE (Drop If Exists) statements instead of big IF wrappers
ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name
I'd prefer INFORMATION_SCHEMA.COLUMNS over a system table because Microsoft does not guarantee to preserve the system tables between versions. For example, dbo.syscolumns does still work in SQL Server 2008, but it's deprecated and could be removed at any time in future.
You can use the information schema system views to find out pretty much anything about the tables you're interested in:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'yourTableName'
ORDER BY ORDINAL_POSITION
You can also interrogate views, stored procedures and pretty much anything about the database using the Information_schema views.
Try something like:
CREATE FUNCTION ColumnExists(#TableName varchar(100), #ColumnName varchar(100))
RETURNS varchar(1) AS
BEGIN
DECLARE #Result varchar(1);
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = #TableName AND COLUMN_NAME = #ColumnName)
BEGIN
SET #Result = 'T'
END
ELSE
BEGIN
SET #Result = 'F'
END
RETURN #Result;
END
GO
GRANT EXECUTE ON [ColumnExists] TO [whoever]
GO
Then use it like this:
IF ColumnExists('xxx', 'yyyy') = 'F'
BEGIN
ALTER TABLE xxx
ADD yyyyy varChar(10) NOT NULL
END
GO
It should work on both SQL Server 2000 and SQL Server 2005. I am not sure about SQL Server 2008, but I don't see why not.
First check if the table/column(id/name) combination exists in dbo.syscolumns (an internal SQL Server table that contains field definitions), and if not issue the appropriate ALTER TABLE query to add it. For example:
IF NOT EXISTS ( SELECT *
FROM syscolumns
WHERE id = OBJECT_ID('Client')
AND name = 'Name' )
ALTER TABLE Client
ADD Name VARCHAR(64) NULL
A good friend and colleague of mine showed me how you can also use an IF block with SQL functions OBJECT_ID and COLUMNPROPERTY in SQL Server 2005 and later to check for a column. You can use something similar to the following:
You can see for yourself here:
IF (OBJECT_ID(N'[dbo].[myTable]') IS NOT NULL AND
COLUMNPROPERTY( OBJECT_ID(N'[dbo].[myTable]'), 'ThisColumnDoesNotExist', 'ColumnId') IS NULL)
BEGIN
SELECT 'Column does not exist -- You can add TSQL to add the column here'
END
declare #myColumn as nvarchar(128)
set #myColumn = 'myColumn'
if not exists (
select 1
from information_schema.columns columns
where columns.table_catalog = 'myDatabase'
and columns.table_schema = 'mySchema'
and columns.table_name = 'myTable'
and columns.column_name = #myColumn
)
begin
exec('alter table myDatabase.mySchema.myTable add'
+' ['+#myColumn+'] bigint null')
end
This worked for me in SQL Server 2000:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_name'
AND column_name = 'column_name'
)
BEGIN
...
END
Try this
SELECT COLUMNS.*
FROM INFORMATION_SCHEMA.COLUMNS COLUMNS,
INFORMATION_SCHEMA.TABLES TABLES
WHERE COLUMNS.TABLE_NAME = TABLES.TABLE_NAME
AND Upper(COLUMNS.COLUMN_NAME) = Upper('column_name')
I needed something similar for SQL Server 2000 and, as Mitch points out, this only works in SQL Server 2005 or later.
This is what worked for me in the end:
if exists (
select *
from
sysobjects, syscolumns
where
sysobjects.id = syscolumns.id
and sysobjects.name = 'table'
and syscolumns.name = 'column')
IF NOT EXISTS(SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'TableName'
AND table_schema = 'SchemaName'
AND column_name = 'ColumnName') BEGIN
ALTER TABLE [SchemaName].[TableName] ADD [ColumnName] int(1) NOT NULL default '0';
END;
if exists (
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = '<table_name>'
and COLUMN_NAME = '<column_name>'
) begin
print 'Column you have specified exists'
end else begin
print 'Column does not exist'
end
One of the simplest and understandable solutions is:
IF COL_LENGTH('Table_Name','Column_Name') IS NULL
BEGIN
-- Column Not Exists, implement your logic
END
ELSE
BEGIN
-- Column Exists, implement your logic
END
A temporary table version of the accepted answer:
if (exists(select 1
from tempdb.sys.columns
where Name = 'columnName'
and Object_ID = object_id('tempdb..#tableName')))
begin
...
end
select distinct object_name(sc.id)
from syscolumns sc,sysobjects so
where sc.name like '%col_name%' and so.type='U'
There are several ways to check the existence of a column.
I would strongly recommend to use INFORMATION_SCHEMA.COLUMNS as it is created in order to communicate with user.
Consider following tables:
sys.objects
sys.columns
and even some other access methods available to check system catalog.
Also, no need to use SELECT *, simply test it by NULL value
IF EXISTS(
SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName'
)
Wheat's answer is good, but it assumes you do not have any identical table name / column name pairs in any schema or database. To make it safe for that condition, use this...
select *
from Information_Schema.Columns
where Table_Catalog = 'DatabaseName'
and Table_Schema = 'SchemaName'
and Table_Name = 'TableName'
and Column_Name = 'ColumnName'
Do something if the column does not exist:
BEGIN
IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NULL)
BEGIN
// Do something
END
END;
Do something if the column does exist:
BEGIN
IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NOT NULL)
BEGIN
// Do something
END
END;
Here is a simple script I use to manage addition of columns in the database:
IF NOT EXISTS (
SELECT *
FROM sys.Columns
WHERE Name = N'QbId'
AND Object_Id = Object_Id(N'Driver')
)
BEGIN
ALTER TABLE Driver ADD QbId NVARCHAR(20) NULL
END
ELSE
BEGIN
PRINT 'QbId is already added on Driver'
END
In this example, the Name is the ColumnName to be added and Object_Id is the TableName
Another contribution is the following sample that adds the column if it does not exist.
USE [Northwind]
GO
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Categories'
AND COLUMN_NAME = 'Note')
BEGIN
ALTER TABLE Categories ADD Note NVARCHAR(800) NULL
END
GO
The below query can be used to check whether searched column exists or not in the table. We can take a decision based on the searched result, also as shown below.
IF EXISTS (SELECT 'Y' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = <YourTableName> AND COLUMN_NAME = <YourColumnName>)
BEGIN
SELECT 'Column Already Exists.'
END
ELSE
BEGIN
ALTER TABLE <YourTableName> ADD <YourColumnName> <DataType>[Size]
END
Yet another variation...
SELECT
Count(*) AS existFlag
FROM
sys.columns
WHERE
[name] = N 'ColumnName'
AND [object_id] = OBJECT_ID(N 'TableName')
You can check multiple columns in SQLDB at once and return a string as status to check if columns exist:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table Name'
AND(COLUMN_NAME = 'column 1'
or COLUMN_NAME = 'column 2'
or COLUMN_NAME = 'column 3'
or COLUMN_NAME = 'column 4')
)
SELECT 'Column exists in table' AS[Status];
ELSE
SELECT 'Column does not exist in table' AS[Status];
Execute the below query to check if the column exists in the given table:
IF(SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') IS NOT NULL
PRINT 'Column Exists in the given table';
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'Database Name'
and TABLE_SCHEMA = 'Schema Name'
and TABLE_NAME = 'Table Name'
and COLUMN_NAME = 'Column Name'
and DATA_TYPE = 'Column Type') -- Where statement lines can be deleted.
BEGIN
-- Column exists in table
END
ELSE BEGIN
-- Column does not exist in table
END
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
This should be the fairly easier way and straightforward solution to this problem. I have used this multiple times for similar scenarios. It works like a charm, no doubts on that.
Is it possible to list information about the files (MDF/LDF) of all databases on an SQL Server?
I'd like to get a list showing which database is using what files on the local disk.
What I tried:
exec sp_databases all databases
select * from sys.databases shows a lot of information about each database - but unfortunately it doesn't show the files used by each database.
select * from sys.database_files shows the mdf/ldf files of the master database - but not the other databases
You can use sys.master_files.
Contains a row per file of a database as stored in the master
database. This is a single, system-wide view.
If you want get location of Database you can check Get All DBs Location.
you can use sys.master_files for get location of db and sys.database to get db name
SELECT
db.name AS DBName,
type_desc AS FileType,
Physical_Name AS Location
FROM
sys.master_files mf
INNER JOIN
sys.databases db ON db.database_id = mf.database_id
I am using script to get empty space in each file:
Create Table ##temp
(
DatabaseName sysname,
Name sysname,
physical_name nvarchar(500),
size decimal (18,2),
FreeSpace decimal (18,2)
)
Exec sp_msforeachdb '
Use [?];
Insert Into ##temp (DatabaseName, Name, physical_name, Size, FreeSpace)
Select DB_NAME() AS [DatabaseName], Name, physical_name,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) as nvarchar) Size,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) -
Cast(FILEPROPERTY(name, ''SpaceUsed'') * 8.0/1024.0 as decimal(18,2)) as nvarchar) As FreeSpace
From sys.database_files
'
Select * From ##temp
drop table ##temp
Size is expressed in KB.
I've created this query:
SELECT
db.name AS [Database Name],
mf.name AS [Logical Name],
mf.type_desc AS [File Type],
mf.physical_name AS [Path],
CAST(
(mf.Size * 8
) / 1024.0 AS DECIMAL(18, 1)) AS [Initial Size (MB)],
'By '+IIF(
mf.is_percent_growth = 1, CAST(mf.growth AS VARCHAR(10))+'%', CONVERT(VARCHAR(30), CAST(
(mf.growth * 8
) / 1024.0 AS DECIMAL(18, 1)))+' MB') AS [Autogrowth],
IIF(mf.max_size = 0, 'No growth is allowed', IIF(mf.max_size = -1, 'Unlimited', CAST(
(
CAST(mf.max_size AS BIGINT) * 8
) / 1024 AS VARCHAR(30))+' MB')) AS [MaximumSize]
FROM
sys.master_files AS mf
INNER JOIN sys.databases AS db ON
db.database_id = mf.database_id
Executing following sql (It will only work when you don't have multiple mdf/ldf files for same database)
SELECT
db.name AS DBName,
(select mf.Physical_Name FROM sys.master_files mf where mf.type_desc = 'ROWS' and db.database_id = mf.database_id ) as DataFile,
(select mf.Physical_Name FROM sys.master_files mf where mf.type_desc = 'LOG' and db.database_id = mf.database_id ) as LogFile
FROM sys.databases db
will return this output
DBName DataFile LogFile
--------------------------------------------------------------------------------
master C:\....\master.mdf C:\....\mastlog.ldf
tempdb C:\....\tempdb.mdf C:\....\templog.ldf
model C:\....\model.mdf C:\....\modellog.ldf
and rest of the databases
If your TempDB's have multiple MDF's (like mine have), this script will fail.
However, you can use
WHERE db.database_id > 4
at the end and it will return all databases except system databases.
You can also try this.
select db_name(dbid) dbname, filename from sys.sysaltfiles
Below script can be used to get following information:
1. DB Size Info
2. FileSpaceInfo
3. AutoGrowth
4. Recovery Model
5. Log_reuse_backup information
CREATE TABLE #tempFileInformation
(
DBNAME NVARCHAR(256),
[FILENAME] NVARCHAR(256),
[TYPE] NVARCHAR(120),
FILEGROUPNAME NVARCHAR(120),
FILE_LOCATION NVARCHAR(500),
FILESIZE_MB DECIMAL(10,2),
USEDSPACE_MB DECIMAL(10,2),
FREESPACE_MB DECIMAL(10,2),
AUTOGROW_STATUS NVARCHAR(100)
)
GO
DECLARE #SQL VARCHAR(2000)
SELECT #SQL = '
USE [?]
INSERT INTO #tempFileInformation
SELECT
DBNAME =DB_NAME(),
[FILENAME] =A.NAME,
[TYPE] = A.TYPE_DESC,
FILEGROUPNAME = fg.name,
FILE_LOCATION =a.PHYSICAL_NAME,
FILESIZE_MB = CONVERT(DECIMAL(10,2),A.SIZE/128.0),
USEDSPACE_MB = CONVERT(DECIMAL(10,2),(A.SIZE/128.0 - ((A.SIZE - CAST(FILEPROPERTY(A.NAME,''SPACEUSED'') AS INT))/128.0))),
FREESPACE_MB = CONVERT(DECIMAL(10,2),(A.SIZE/128.0 - CAST(FILEPROPERTY(A.NAME,''SPACEUSED'') AS INT)/128.0)),
AUTOGROW_STATUS = ''BY '' +CASE is_percent_growth when 0 then cast (growth/128 as varchar(10))+ '' MB - ''
when 1 then cast (growth as varchar(10)) + ''% - '' ELSE '''' END
+ CASE MAX_SIZE WHEN 0 THEN '' DISABLED ''
WHEN -1 THEN '' UNRESTRICTED''
ELSE '' RESTRICTED TO '' + CAST(MAX_SIZE/(128*1024) AS VARCHAR(10)) + '' GB '' END
+ CASE IS_PERCENT_GROWTH WHEn 1 then '' [autogrowth by percent]'' else '''' end
from sys.database_files A
left join sys.filegroups fg on a.data_space_id = fg.data_space_id
order by A.type desc,A.name
;
'
--print #sql
EXEC sp_MSforeachdb #SQL
go
SELECT dbSize.*,fg.*,d.log_reuse_wait_desc,d.recovery_model_desc
FROM #tempFileInformation fg
LEFT JOIN sys.databases d on fg.DBNAME = d.name
CROSS APPLY
(
select dbname,
sum(FILESIZE_MB) as [totalDBSize_MB],
sum(FREESPACE_MB) as [DB_Free_Space_Size_MB],
sum(USEDSPACE_MB) as [DB_Used_Space_Size_MB]
from #tempFileInformation
where dbname = fg.dbname
group by dbname
)dbSize
go
DROP TABLE #tempFileInformation
Using this script you can show all the databases name and files used (with exception of system dbs).
select name,physical_name from sys.master_files where database_id > 4
To get around queries which error when multiple data files (e.g. ".ndf" file types) exist, try this version, it replaces the sub-queries with joins.
Here's a version of your query using joins instead of the sub-queries.
Cheers!
SELECT
db.name AS DBName,
db.database_id,
mfr.physical_name AS DataFile,
mfl.physical_name AS LogFile
FROM sys.databases db
JOIN sys.master_files mfr ON db.database_id=mfr.database_id AND mfr.type_desc='ROWS'
JOIN sys.master_files mfl ON db.database_id=mfl.database_id AND mfl.type_desc='LOG'
ORDER BY db.database_id
Sample Results:
(Please note, the single log file is paired with each MDF and NDF for a single database)
This script lists most of what you are looking for and can hopefully be modified to you needs. Note that it is creating a permanent table in there - you might want to change it. It is a subset from a larger script that also summarises backup and job information on various servers.
IF OBJECT_ID('tempdb..#DriveInfo') IS NOT NULL
DROP TABLE #DriveInfo
CREATE TABLE #DriveInfo
(
Drive CHAR(1)
,MBFree INT
)
INSERT INTO #DriveInfo
EXEC master..xp_fixeddrives
IF OBJECT_ID('[dbo].[Tmp_tblDatabaseInfo]', 'U') IS NOT NULL
DROP TABLE [dbo].[Tmp_tblDatabaseInfo]
CREATE TABLE [dbo].[Tmp_tblDatabaseInfo](
[ServerName] [nvarchar](128) NULL
,[DBName] [nvarchar](128) NULL
,[database_id] [int] NULL
,[create_date] datetime NULL
,[CompatibilityLevel] [int] NULL
,[collation_name] [nvarchar](128) NULL
,[state_desc] [nvarchar](60) NULL
,[recovery_model_desc] [nvarchar](60) NULL
,[DataFileLocations] [nvarchar](4000)
,[DataFilesMB] money null
,DataVolumeFreeSpaceMB INT NULL
,[LogFileLocations] [nvarchar](4000)
,[LogFilesMB] money null
,LogVolumeFreeSpaceMB INT NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Tmp_tblDatabaseInfo]
SELECT
##SERVERNAME AS [ServerName]
,d.name AS DBName
,d.database_id
,d.create_date
,d.compatibility_level
,CAST(d.collation_name AS [nvarchar](128)) AS collation_name
,d.[state_desc]
,d.recovery_model_desc
,(select physical_name + ' | ' AS [text()]
from sys.master_files m
WHERE m.type = 0 and m.database_id = d.database_id
ORDER BY file_id
FOR XML PATH ('')) AS DataFileLocations
,(select sum(size) from sys.master_files m WHERE m.type = 0 and m.database_id = d.database_id) AS DataFilesMB
,NULL
,(select physical_name + ' | ' AS [text()]
from sys.master_files m
WHERE m.type = 1 and m.database_id = d.database_id
ORDER BY file_id
FOR XML PATH ('')) AS LogFileLocations
,(select sum(size) from sys.master_files m WHERE m.type = 1 and m.database_id = d.database_id) AS LogFilesMB
,NULL
FROM sys.databases d
WHERE d.database_id > 4 --Exclude basic system databases
UPDATE [dbo].[Tmp_tblDatabaseInfo]
SET DataFileLocations =
CASE WHEN LEN(DataFileLocations) > 4 THEN LEFT(DataFileLocations,LEN(DataFileLocations)-2) ELSE NULL END
,LogFileLocations =
CASE WHEN LEN(LogFileLocations) > 4 THEN LEFT(LogFileLocations,LEN(LogFileLocations)-2) ELSE NULL END
,DataFilesMB =
CASE WHEN DataFilesMB > 0 THEN DataFilesMB * 8 / 1024.0 ELSE NULL END
,LogFilesMB =
CASE WHEN LogFilesMB > 0 THEN LogFilesMB * 8 / 1024.0 ELSE NULL END
,DataVolumeFreeSpaceMB =
(SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( DataFileLocations,1))
,LogVolumeFreeSpaceMB =
(SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( LogFileLocations,1))
select * from [dbo].[Tmp_tblDatabaseInfo]
If you rename your Database, MS SQL Server does not rename the underlying files.
Following query gives you the current name of the database and the Logical file name (which might be the original name of the Database when it was created) and also corresponding physical file names.
Note: Un-comment the last line to see only the actual data files
select db.database_id,
db.name "Database Name",
files.name "Logical File Name",
files.physical_name
from sys.master_files files
join sys.databases db on db.database_id = files.database_id
-- and files.type_desc = 'ROWS'
Reference:
https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-master-files-transact-sql?view=sql-server-ver15
https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-databases-transact-sql?view=sql-server-ver15
Using the sp_MSForEachDB stored procedure is an option
EXEC sp_MSForEachDB 'use ? select * from sys.database_files'
Additionally to see just the Full Path name and size information
EXEC sp_MSForEachDB '
USE [?];
SELECT DB_NAME() AS DbName,
physical_name AS FullPath,
name AS FileName,
type_desc,
size/128.0 AS CurrentSizeMB,
size/128.0 - CAST(FILEPROPERTY(name, ''SpaceUsed'') AS INT)/128.0 AS FreeSpaceMB
FROM sys.database_files
WHERE type IN (0,1);
'
just adding my 2 cents .
if specifically looking to find total free space only in Data files or only in Log files in all the databases, we can use "data_space_id" column. 1 is for data files and 0 for log files.
CODE:
Create Table ##temp
(
DatabaseName sysname,
Name sysname,
spacetype sysname,
physical_name nvarchar(500),
size decimal (18,2),
FreeSpace decimal (18,2)
)
Exec sp_msforeachdb '
Use [?];
Insert Into ##temp (DatabaseName, Name,spacetype, physical_name, Size, FreeSpace)
Select DB_NAME() AS [DatabaseName], Name, ***data_space_id*** , physical_name,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2))/1024 as nvarchar) SizeGB,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2)/1024 as decimal(18,2)) -
Cast(FILEPROPERTY(name, ''SpaceUsed'') * 8.0/1024.0 as decimal(18,2))/1024 as nvarchar) As FreeSpaceGB
From sys.database_files'
select
databasename
, sum(##temp.FreeSpace)
from
##temp
where
##temp.spacetype = 1
group by
DatabaseName
drop table ##temp
Also you can use this SQL query for retrieving files list :
SELECT d.name AS DatabaseName,
m.name AS LogicalName,
m.physical_name AS PhysicalName,
size AS FileSize
FROM sys.master_files m
INNER JOIN sys.databases d ON(m.database_id = d.database_id)
where d.name = '<Database Name>'
ORDER BY physical_name ;
You can use the below:
SP_HELPDB [Master]
GO
Question: In SQL Server 2005, how can I list all SQL CLR-functions/procedures that use assembly xy (e.g. MyFirstUdp) ?
For example a function that lists HelloWorld for query parameter MyFirstUdp
CREATE PROCEDURE HelloWorld
AS EXTERNAL NAME MyFirstUdp.[SQL_CLRdll.MySQLclass].HelloWorld
GO
after I ran
CREATE ASSEMBLY MyFirstUdp FROM 'C:\Users\username\Documents\Visual Studio 2005\Projects\SQL_CLRdll\SQL_CLRdll\bin\Debug\SQL_CLRdll.dll
I can list all assemblies and all functions/procedures,
but I seem to be unable to associate the assembly to the functions/procedures...
Check out the sys.assembly_modules view:
select * from sys.assembly_modules
This should list all functions and the assemblies they're defined in. See the Books Online help page about it.
Returns one row for each function,
procedure or trigger that is defined
by a common language runtime (CLR)
assembly.
I use the following SQL:
SELECT so.name AS [ObjectName],
so.[type],
SCHEMA_NAME(so.[schema_id]) AS [SchemaName],
asmbly.name AS [AssemblyName],
asmbly.permission_set_desc,
am.assembly_class,
am.assembly_method
FROM sys.assembly_modules am
INNER JOIN sys.assemblies asmbly
ON asmbly.assembly_id = am.assembly_id
AND asmbly.is_user_defined = 1 -- if using SQL Server 2008 or newer
-- AND asmbly.name NOT LIKE 'Microsoft%' -- if using SQL Server 2005
INNER JOIN sys.objects so
ON so.[object_id] = am.[object_id]
UNION ALL
SELECT at.name AS [ObjectName],
'UDT' AS [type],
SCHEMA_NAME(at.[schema_id]) AS [SchemaName],
asmbly.name AS [AssemblyName],
asmbly.permission_set_desc,
at.assembly_class,
NULL AS [assembly_method]
FROM sys.assembly_types at
INNER JOIN sys.assemblies asmbly
ON asmbly.assembly_id = at.assembly_id
AND asmbly.is_user_defined = 1 -- if using SQL Server 2008 or newer
-- AND asmbly.name NOT LIKE 'Microsoft%' -- if using SQL Server 2005
ORDER BY [AssemblyName], [type], [ObjectName]
Please note:
User-Defined Types (UDTs) are found in: sys.assembly_types
You can only list SQLCLR references that have been used in CREATE { PROCEDURE | FUNCTION | AGGREGATE | TRIGGER | TYPE } statements. You cannot find SQLCLR methods that have not yet been referenced by a CREATE. Meaning, you cannot say: "give me a list of methods in this assembly that I can create T-SQL objects for".
For more info on working with SQLCLR in general, please visit: SQLCLR Info
Here is a generalization of srutzky's query (above) that goes through all DBs on a server using a cursor. Sorry about the formatting, but this is handy if you have to search through 500 DB's you've inherited.
set nocount on
declare #cmd nvarchar(4000)
declare curDBs cursor read_only for
SELECT name FROM MASTER.sys.sysdatabases
declare #NameDB nvarchar(100)
create table #tmpResults (
DatabaseName nvarchar(128)
, ObjectName nvarchar(128)
, ObjectType char(2)
, SchemaName nvarchar(128)
, AssemblyName nvarchar(128)
, PermissionSet nvarchar(60)
, AssemblyClass nvarchar(128)
, AssemblyMethod nvarchar(128));
open curDBs; while (1=1)
begin
fetch next from curDBs into #NameDB
if ##fetch_status <> 0 break
set #cmd = N'
USE [' + #NameDB + N'];
begin try
insert into #tmpResults
SELECT ''' + #NameDB + N''',
so.name AS [ObjectName],
so.[type],
SCHEMA_NAME(so.[schema_id]) AS [SchemaName],
asy.name AS [AssemblyName],
asy.permission_set_desc,
am.assembly_class,
am.assembly_method
FROM sys.assembly_modules am
INNER JOIN sys.assemblies asy
ON asy.assembly_id = am.assembly_id
AND asy.is_user_defined = 1
INNER JOIN sys.objects so
ON so.[object_id] = am.[object_id]
UNION ALL
SELECT ''' + #NameDB + N''',
at.name AS [ObjectName],
''UDT'' AS [type],
SCHEMA_NAME(at.[schema_id]) AS [SchemaName],
asy.name AS [AssemblyName],
asy.permission_set_desc,
at.assembly_class,
NULL AS [assembly_method]
FROM sys.assembly_types at
INNER JOIN sys.assemblies asy
ON asy.assembly_id = at.assembly_id
AND asy.is_user_defined = 1
ORDER BY [AssemblyName], [type], [ObjectName]
print ''' + #NameDB + N' ' + cast(##rowcount as nvarchar) + N'''
end try
begin catch
print ''Error processing ' + #NameDB + '''
end catch
'
--print #cmd
EXEC sp_executesql #cmd
end
close curDBs; deallocate curDBs
select * from #tmpResults
drop table #tmpResults
Here it a script found on sqlhint.com:
SELECT
SCHEMA_NAME(O.schema_id) AS [Schema], O.name,
A.name AS assembly_name, AM.assembly_class,
AM.assembly_method,
A.permission_set_desc,
O.[type_desc]
FROM
sys.assembly_modules AM
INNER JOIN sys.assemblies A ON A.assembly_id = AM.assembly_id
INNER JOIN sys.objects O ON O.object_id = AM.object_id
ORDER BY
A.name, AM.assembly_class
Also, you have the option to see all the places where that CLR object is used.
SELECT
modules.assembly_class AS AssemblyClass,
modules.assembly_method AS MethodName,
obj.type_desc AS MethodType,
files.name AS FilePath,
assemb.name AS AssemblyName,
assemb.clr_name,
assemb.create_date,
assemb.modify_date,
assemb.permission_set_desc
--,*
FROM
sys.assembly_modules AS modules
JOIN sys.assembly_files AS files ON files.assembly_id = modules.assembly_id
JOIN sys.assemblies AS assemb ON assemb.assembly_id = modules.assembly_id
JOIN sys.objects AS obj ON obj.object_id = modules.object_id
Or you can use
SELECT * FROM sys.dm_clr_appdomains;
which returns a list of assemblies and in what database they are stored.
I need to add a specific column if it does not exist. I have something like the following, but it always returns false:
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName')
How can I check if a column exists in a table of the SQL Server database?
SQL Server 2005 onwards:
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
-- Column Exists
END
Martin Smith's version is shorter:
IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column Exists
END
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.
Tweak the below to suit your specific requirements:
if not exists (select
column_name
from
INFORMATION_SCHEMA.columns
where
table_name = 'MyTable'
and column_name = 'MyColumn')
alter table MyTable add MyColumn int
That should work - take a careful look over your code for stupid mistakes; are you querying INFORMATION_SCHEMA on the same database as your insert is being applied to for example? Do you have a typo in your table/column name in either statement?
Try this...
IF NOT EXISTS(
SELECT TOP 1 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
[TABLE_NAME] = 'Employees'
AND [COLUMN_NAME] = 'EmployeeID')
BEGIN
ALTER TABLE [Employees]
ADD [EmployeeID] INT NULL
END
For the people who are checking the column existence before dropping it.
From SQL Server 2016 you can use new DIE (Drop If Exists) statements instead of big IF wrappers
ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name
I'd prefer INFORMATION_SCHEMA.COLUMNS over a system table because Microsoft does not guarantee to preserve the system tables between versions. For example, dbo.syscolumns does still work in SQL Server 2008, but it's deprecated and could be removed at any time in future.
You can use the information schema system views to find out pretty much anything about the tables you're interested in:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'yourTableName'
ORDER BY ORDINAL_POSITION
You can also interrogate views, stored procedures and pretty much anything about the database using the Information_schema views.
Try something like:
CREATE FUNCTION ColumnExists(#TableName varchar(100), #ColumnName varchar(100))
RETURNS varchar(1) AS
BEGIN
DECLARE #Result varchar(1);
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = #TableName AND COLUMN_NAME = #ColumnName)
BEGIN
SET #Result = 'T'
END
ELSE
BEGIN
SET #Result = 'F'
END
RETURN #Result;
END
GO
GRANT EXECUTE ON [ColumnExists] TO [whoever]
GO
Then use it like this:
IF ColumnExists('xxx', 'yyyy') = 'F'
BEGIN
ALTER TABLE xxx
ADD yyyyy varChar(10) NOT NULL
END
GO
It should work on both SQL Server 2000 and SQL Server 2005. I am not sure about SQL Server 2008, but I don't see why not.
First check if the table/column(id/name) combination exists in dbo.syscolumns (an internal SQL Server table that contains field definitions), and if not issue the appropriate ALTER TABLE query to add it. For example:
IF NOT EXISTS ( SELECT *
FROM syscolumns
WHERE id = OBJECT_ID('Client')
AND name = 'Name' )
ALTER TABLE Client
ADD Name VARCHAR(64) NULL
A good friend and colleague of mine showed me how you can also use an IF block with SQL functions OBJECT_ID and COLUMNPROPERTY in SQL Server 2005 and later to check for a column. You can use something similar to the following:
You can see for yourself here:
IF (OBJECT_ID(N'[dbo].[myTable]') IS NOT NULL AND
COLUMNPROPERTY( OBJECT_ID(N'[dbo].[myTable]'), 'ThisColumnDoesNotExist', 'ColumnId') IS NULL)
BEGIN
SELECT 'Column does not exist -- You can add TSQL to add the column here'
END
declare #myColumn as nvarchar(128)
set #myColumn = 'myColumn'
if not exists (
select 1
from information_schema.columns columns
where columns.table_catalog = 'myDatabase'
and columns.table_schema = 'mySchema'
and columns.table_name = 'myTable'
and columns.column_name = #myColumn
)
begin
exec('alter table myDatabase.mySchema.myTable add'
+' ['+#myColumn+'] bigint null')
end
This worked for me in SQL Server 2000:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_name'
AND column_name = 'column_name'
)
BEGIN
...
END
Try this
SELECT COLUMNS.*
FROM INFORMATION_SCHEMA.COLUMNS COLUMNS,
INFORMATION_SCHEMA.TABLES TABLES
WHERE COLUMNS.TABLE_NAME = TABLES.TABLE_NAME
AND Upper(COLUMNS.COLUMN_NAME) = Upper('column_name')
I needed something similar for SQL Server 2000 and, as Mitch points out, this only works in SQL Server 2005 or later.
This is what worked for me in the end:
if exists (
select *
from
sysobjects, syscolumns
where
sysobjects.id = syscolumns.id
and sysobjects.name = 'table'
and syscolumns.name = 'column')
IF NOT EXISTS(SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'TableName'
AND table_schema = 'SchemaName'
AND column_name = 'ColumnName') BEGIN
ALTER TABLE [SchemaName].[TableName] ADD [ColumnName] int(1) NOT NULL default '0';
END;
if exists (
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = '<table_name>'
and COLUMN_NAME = '<column_name>'
) begin
print 'Column you have specified exists'
end else begin
print 'Column does not exist'
end
One of the simplest and understandable solutions is:
IF COL_LENGTH('Table_Name','Column_Name') IS NULL
BEGIN
-- Column Not Exists, implement your logic
END
ELSE
BEGIN
-- Column Exists, implement your logic
END
A temporary table version of the accepted answer:
if (exists(select 1
from tempdb.sys.columns
where Name = 'columnName'
and Object_ID = object_id('tempdb..#tableName')))
begin
...
end
select distinct object_name(sc.id)
from syscolumns sc,sysobjects so
where sc.name like '%col_name%' and so.type='U'
There are several ways to check the existence of a column.
I would strongly recommend to use INFORMATION_SCHEMA.COLUMNS as it is created in order to communicate with user.
Consider following tables:
sys.objects
sys.columns
and even some other access methods available to check system catalog.
Also, no need to use SELECT *, simply test it by NULL value
IF EXISTS(
SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName'
)
Wheat's answer is good, but it assumes you do not have any identical table name / column name pairs in any schema or database. To make it safe for that condition, use this...
select *
from Information_Schema.Columns
where Table_Catalog = 'DatabaseName'
and Table_Schema = 'SchemaName'
and Table_Name = 'TableName'
and Column_Name = 'ColumnName'
Do something if the column does not exist:
BEGIN
IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NULL)
BEGIN
// Do something
END
END;
Do something if the column does exist:
BEGIN
IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NOT NULL)
BEGIN
// Do something
END
END;
Here is a simple script I use to manage addition of columns in the database:
IF NOT EXISTS (
SELECT *
FROM sys.Columns
WHERE Name = N'QbId'
AND Object_Id = Object_Id(N'Driver')
)
BEGIN
ALTER TABLE Driver ADD QbId NVARCHAR(20) NULL
END
ELSE
BEGIN
PRINT 'QbId is already added on Driver'
END
In this example, the Name is the ColumnName to be added and Object_Id is the TableName
Another contribution is the following sample that adds the column if it does not exist.
USE [Northwind]
GO
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Categories'
AND COLUMN_NAME = 'Note')
BEGIN
ALTER TABLE Categories ADD Note NVARCHAR(800) NULL
END
GO
The below query can be used to check whether searched column exists or not in the table. We can take a decision based on the searched result, also as shown below.
IF EXISTS (SELECT 'Y' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = <YourTableName> AND COLUMN_NAME = <YourColumnName>)
BEGIN
SELECT 'Column Already Exists.'
END
ELSE
BEGIN
ALTER TABLE <YourTableName> ADD <YourColumnName> <DataType>[Size]
END
Yet another variation...
SELECT
Count(*) AS existFlag
FROM
sys.columns
WHERE
[name] = N 'ColumnName'
AND [object_id] = OBJECT_ID(N 'TableName')
You can check multiple columns in SQLDB at once and return a string as status to check if columns exist:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table Name'
AND(COLUMN_NAME = 'column 1'
or COLUMN_NAME = 'column 2'
or COLUMN_NAME = 'column 3'
or COLUMN_NAME = 'column 4')
)
SELECT 'Column exists in table' AS[Status];
ELSE
SELECT 'Column does not exist in table' AS[Status];
Execute the below query to check if the column exists in the given table:
IF(SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') IS NOT NULL
PRINT 'Column Exists in the given table';
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'Database Name'
and TABLE_SCHEMA = 'Schema Name'
and TABLE_NAME = 'Table Name'
and COLUMN_NAME = 'Column Name'
and DATA_TYPE = 'Column Type') -- Where statement lines can be deleted.
BEGIN
-- Column exists in table
END
ELSE BEGIN
-- Column does not exist in table
END
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
This should be the fairly easier way and straightforward solution to this problem. I have used this multiple times for similar scenarios. It works like a charm, no doubts on that.