How do I check if a column exists in SQL Server? - sql-server

How do I check if a column exists in SQL Server 2000?

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tablename' AND COLUMN_NAME='columname' )

If col_length('table_name','column_name') is null
select 0 as Present
ELSE
select 1 as Present
Present will be 0, is there is no column_name present in table_name , otherwise 1
#CMS: I don't think that 'INFORMATION_SCHEMA.COLUMNS' have information about every table in DB. Because this didn't worked for me. But my answer did worked.

In query analyzer, select the Database that contains the table in which you need to check if the field exists or not and run the query below.
SELECT count(*) AS [Column Exists]
FROM SYSOBJECTS
INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID
WHERE
SYSOBJECTS.NAME = 'myTable'
AND SYSCOLUMNS.NAME = 'Myfield'

This should do nicely:
if COLUMNPROPERTY(object_id('table_name'), 'column_name', 'ColumnId') is null
print 'doesn\'t exist'
else
print 'exists'

I don't know if this script will work in sqlserver 2000, but in 2008 works:
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')

Related

How to retrieve all record from every table where id = 1 in MS SQL Server 2008 R2

How do I retrieve all record from every table (Ex: table1, table2, table3, ... tableN ) where id = 1 from single database (EX: database1) in SQL Server 2008 R2?
Let's suppose I have 1 database and in that I have infinite tables (EX. table1,table2, ....,tableN). Is this possible to get all the record from entire database where id=1 on each table? I think it is possible with SQL information_schema.table or information_schema.column, but I don't know how to use this.
Any help appreciated
Thanks in advance!
You can use the undocumented sp_msforeachtable
sp_msforeachtable
#command1 = 'SELECT * FROM ? WHERE id=1',
#whereand = ' And Object_id In (Select Object_id From sys.columns Where name=''id'')'
#command1 is your query. The question mark is a placeholder the stored procedure uses to insert the table name.
#whereand limits the search to just tables that have the column named id
I don't have much idea of MySQL, Use this in db2
Select C.NAME,C.ROLLNUMBER from TABLE1 C,TABLE2 A where C.ROLLNUMBER=A.ROLLNUMBER and id = 1 order by C.CIRCLENAME
hope this will work too..
If you want to mention the tables manually try this.
SELECT COL1,COL2,COL3....COLN FROM TABLE1 WHERE ID=1
UNION ALL
SELECT COL1,COL2,COL3....COLN FROM TABLE2 WHERE ID=1
UNION ALL
SELECT COL1,COL2,COL3....COLN FROM TABLE2 WHERE ID=1
:
:
:
UNION ALL
SELECT COL1,COL2,COL3....COLN FROM TABLEN WHERE ID=1
Note: The col1,col2,col3...coln Should Be Same Datatype in All The Mentioned Tables
This for dynamic building of all the tables with id =1
SELECT STUFF((SELECT '
UNION ALL
SELECT COL1,COL2,COL3..COLN FROM '+TABLE_NAME + ' WHERE ID=1 '
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' FOR XML PATH(''),type).value('.', 'NVARCHAR(MAX)'),1,11,'')
Note:Your tables must contain the common column i.e ID .change the column names as per you need but all the mentioned columns in select statement should be contain in all of your tables.
The best possible way would be to generate a dynamic query and executed it to get the required information.
To generate the query you can use the schema information related system tables and feed the data in a fixed format table. i.e. make a fix format tables having a defined column structure. That will help to feed the data.
For example:
CREATE TABLE AllTableData
(
TableId int,
TableName nvarchar(250),
TableData NVARCHAR(max),
SelectedId int
)
Where TableId is the id of table from system table and TableData will contain the concatenated value string of all columns of a table with some separator identifier.
;WITH T AS
(
SELECT
T1.*
FROM
INFORMATION_SCHEMA.TABLES T1
INNER JOIN INFORMATION_SCHEMA.COLUMNS T2 ON T2.TABLE_NAME = T2.TABLE_NAME
WHERE
T2.COLUMN_NAME = 'Id'
AND T1.TABLE_TYPE='BASE TABLE'
),
DynamicQuery AS (
SELECT
1 AS Id,
CONCAT(
'SELECT ', QUOTENAME(T.TABLE_NAME,''''),' AS [TableName],',
CONCAT(' CONCAT(',STUFF((SELECT CONCAT(', [' , C.COLUMN_NAME,']' )
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME = T.TABLE_NAME
FOR XML PATH('')), 1, 1, ''),') AS [TableData]'
)
,', 1 AS [SelectedId] FROM ', T.TABLE_NAME,' WHERE Id = 1'
) [FinalString]
FROM T
)
SELECT DISTINCT
STUFF((SELECT ' UNION ALL ' + DQ2.FinalString
FROM DynamicQuery DQ2
WHERE DQ2.Id = DQ1.Id
FOR XML PATH('')), 1, 10, '') [FinalString]
FROM DynamicQuery DQ1
GROUP BY DQ1.Id, DQ1.FinalString
I think, this is what you are searching for.

list all tables from a database in syBase

In sql server 2012 i'm using
USE myDatabase;
GO
SELECT *
FROM sys.objects
WHERE type = 'U';
Is it possible to do the same in syBase ?
In order to get a list of all tables in the current database, you can filter the sysobjects table by type = ‘U’ e.g.:
select convert(varchar(30),o.name) AS table_name
from sysobjects o
where type = 'U'
order by table_name
Further Reference
Here is an example of getting all table names in MSSQL or SQL Server database:
USE test; //SELECT DATABASE
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'
or you can use sys.tables to get all table names from selected database as shown in following SQL query
USE test; //SELECT DATABASE
SELECT * FROM sys.tables
That's all on how to find all table names from database in SQL Server.
For SQL Anywhere 16, this query works fine.
select * from sys.SYSTABLE
It gives a list of the table_names along with the information like table id, table page count, etc.
In order to list all the tables and rows count, the following query can be used.
select convert(varchar(30),o.name) AS table_name,
row_count(db_id(), o.id) AS row_count
from sysobjects o
where type = 'U'
order by table_name
In order get a list of tables which has the table name like, use the following query.
Here table_name has to be replaced with your desired name.
select convert(varchar(30),o.name) AS table_name,
row_count(db_id(), o.id) AS row_count
from sysobjects o
where type = 'U' and o.name like '%table_name%'
order by table_name

How to list all the user tables in Sybase along with their row count?

I would like to return all the tables and its count next to it. what is the quickest way to go about it?
I know in Oracle, you can do something like below, but not sure about Sybase:
declare n number;
begin
for rec in (select object_name from user_objects where object_type='TABLE')
loop
execute immediate 'select count(*) from '||rec.object_name into n;
dbms_output.put_line (rec.object_name||':'||n);
end loop;
end;
Here is the Sybase sql that does the above:
select ob.name,st.rowcnt
from sysobjects ob, systabstats st
where ob.type="U"
and st.id=ob.id
order by ob.name
It depends on what Sybase product you mean. In my SQL Anywhere (9 and 11), your solution doesn't work, but this works:
select table_name, count
from systable
where primary_root<>0 and creator=1
order by 1
As there can be multiple entries in systabstats table, the query should be:
select ob.name, sum(st.rowcnt)
from sysobjects ob, systabstats st
where ob.type="U"
and st.id=ob.id
group by ob.name
order by ob.name
If the current user is the creator:
SELECT table_name, count
FROM sys.systable
WHERE creator = user_id()
NOTE: I test this in Sybase ASA 9.
use the below query
select name,row_count(db_id(),id) as "Rows"
from sysobjects where type='U' order by 2 desc
This works for me using "SQL Central" with SQL Anywhere 17:
SELECT table_name, st.count
FROM systable st
WHERE table_type = 'BASE'
select ob.name,st.rowcnt from sysobjects ob, systabstats st where b.type='U'
and st.id=ob.id and indid=0 order by ob.name

Add a column to a table, if it does not already exist

I want to write a query for MS SQL Server that adds a column into a table. But I don't want any error display, when I run/execute the following query.
I am using this sort of query to add a table ...
IF EXISTS (
SELECT *
FROM sys.objects
WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[Person]')
AND TYPE IN (N'U')
)
But I don't know how to write this query for a column.
You can use a similar construct by using the sys.columns table io sys.objects.
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(N'[dbo].[Person]')
AND name = 'ColumnName'
)
IF COL_LENGTH('table_name', 'column_name') IS NULL
BEGIN
ALTER TABLE table_name
ADD [column_name] INT
END
Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.
IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
ALTER TABLE Person
ADD ColumnName VARCHAR(MAX) NOT NULL
END
I also noticed yours is looking for where table does exist that is obviously just this
if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null
Here's another variation that worked for me.
IF NOT EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE upper(TABLE_NAME) = 'TABLENAME'
AND upper(COLUMN_NAME) = 'COLUMNNAME')
BEGIN
ALTER TABLE [dbo].[Person] ADD Column
END
GO
EDIT:
Note that INFORMATION_SCHEMA views may not always be updated, use SYS.COLUMNS instead:
IF NOT EXISTS (SELECT 1
FROM SYS.COLUMNS....
IF NOT EXISTS (SELECT * FROM syscolumns
WHERE ID=OBJECT_ID('[db].[Employee]') AND NAME='EmpName')
ALTER TABLE [db].[Employee]
ADD [EmpName] VARCHAR(10)
GO
I Hope this would help. More info
When checking for a column in another database, you can simply include the database name:
IF NOT EXISTS (
SELECT *
FROM DatabaseName.sys.columns
WHERE object_id = OBJECT_ID(N'[DatabaseName].[dbo].[TableName]')
AND name = 'ColumnName'
)
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE
OBJECT_ID = OBJECT_ID(N'[dbo].[Person]') AND name = 'DateOfBirth')
BEGIN
ALTER TABLE [dbo].[Person] ADD DateOfBirth DATETIME
END

How do I get list of all tables in a database using TSQL?

What is the best way to get the names of all of the tables in a specific database on SQL Server?
SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017 or 2019:
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
To show only tables from a particular database
SELECT TABLE_NAME
FROM [<DATABASE_NAME>].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Or,
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_CATALOG='dbName' --(for MySql, use: TABLE_SCHEMA='dbName' )
PS: For SQL Server 2000:
SELECT * FROM sysobjects WHERE xtype='U'
SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'
Here is a list of other object types you can search for as well:
AF: Aggregate function (CLR)
C: CHECK constraint
D: Default or DEFAULT constraint
F: FOREIGN KEY constraint
L: Log
FN: Scalar function
FS: Assembly (CLR) scalar-function
FT: Assembly (CLR) table-valued function
IF: In-lined table-function
IT: Internal table
P: Stored procedure
PC: Assembly (CLR) stored-procedure
PK: PRIMARY KEY constraint (type is K)
RF: Replication filter stored procedure
S: System table
SN: Synonym
SQ: Service queue
TA: Assembly (CLR) DML trigger
TF: Table function
TR: SQL DML Trigger
TT: Table type
U: User table
UQ: UNIQUE constraint (type is K)
V: View
X: Extended stored procedure
SELECT * FROM INFORMATION_SCHEMA.TABLES
OR
SELECT * FROM Sys.Tables
USE YourDBName
GO
SELECT *
FROM sys.Tables
GO
OR
USE YourDBName
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
GO
SELECT * FROM information_schema.tables
where TABLE_TYPE = 'BASE TABLE'
SQL Server 2012
select * from sysobjects where xtype='U'
exec sp_msforeachtable 'print ''?'''
SELECT name
FROM sysobjects
WHERE xtype='U'
ORDER BY name;
(SQL Server 2000 standard; still supported in SQL Server 2005.)
The downside of INFORMATION_SCHEMA.TABLES is that it also includes system tables such as dtproperties and the MSpeer_... tables, with no way to tell them apart from your own tables.
I would recommend using sys.objects (the new version of the deprecated sysobjects view), which does support excluding the system tables:
select *
from sys.objects
where type = 'U' -- User tables
and is_ms_shipped = 0 -- Exclude system tables
SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'
Well you can use sys.objects to get all database objects.
GO
select * from sys.objects where type_desc='USER_TABLE' order by name
GO
OR
-- For all tables
select * from INFORMATION_SCHEMA.TABLES
GO
--- For user defined tables
select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'
GO
--- For Views
select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='VIEW'
GO
In SSMS, to get all fully qualified table names in a specific database (E.g., "MyDatabase"):
SELECT [TABLE_CATALOG] + '.' + [TABLE_SCHEMA] + '.' + [TABLE_NAME]
FROM MyDatabase.INFORMATION_SCHEMA.Tables
WHERE [TABLE_TYPE] = 'BASE TABLE' and [TABLE_NAME] <> 'sysdiagrams'
ORDER BY [TABLE_SCHEMA], [TABLE_NAME]
Results:
MyDatabase.dbo.MyTable1
MyDatabase.dbo.MyTable2
MyDatabase.MySchema.MyTable3
MyDatabase.MySchema.MyTable4
etc.
Any of the T-SQL code below will work in SQL Server 2019:
-- here, you need to prefix the database name in INFORMATION_SCHEMA.TABLES
SELECT TABLE_NAME FROM [MSSQL-TEST].INFORMATION_SCHEMA.TABLES;
-- The next 2 ways will require you to point
-- to the specific database you want to list the tables
USE [MSSQL-TEST];
-- (1) Using sys.tables
SELECT * FROM sys.tables;
-- (2) Using sysobjects
SELECT * FROM sysobjects
WHERE type='U';
Here’s a working example using [Skyvia] using sys.tables.
[Skyvia] should be the link to https://skyvia.com/connectors/sql-server
[1]: https://i.stack.imgur.com/o3qo9.png
Your SQL GUI tool should also have a way to list down all the tables in a database like the one above.
So, whatever suits your need and taste, there’s a code or GUI tool for that.
--for oracle
select tablespace_name, table_name from all_tables;
This link can provide much more information on this
topic
Please use this. You will get table names along with schema names:
SELECT SYSSCHEMA.NAME, SYSTABLE.NAME
FROM SYS.tables SYSTABLE
INNER JOIN SYS.SCHEMAS SYSSCHEMA
ON SYSTABLE.SCHEMA_ID = SYSSCHEMA.SCHEMA_ID
UPDATE 2022:
You can list/show the tables that you created with this simple query in Microsoft SQL SERVER.
select * from SYS.TABLES;
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
ORDER BY TABLE_NAME
Thanks to Ray Vega, whose response gives all user tables in a database...
exec sp_msforeachtable 'print ''?'''
sp_helptext shows the underlying query, which summarises to...
select * from dbo.sysobjects o
join sys.all_objects syso on o.id = syso.object_id
where OBJECTPROPERTY(o.id, 'IsUserTable') = 1
and o.category & 2 = 0
Using SELECT * FROM INFORMATION_SCHEMA.COLUMNS also shows you all tables and related columns.
To remove tables added by replication and any other table Microsoft adds run this:
SELECT s.NAME SchemaName, t.NAME TableName
FROM [dbname].SYS.tables t
INNER JOIN [dbname].SYS.SCHEMAS s
ON t.SCHEMA_ID = s.SCHEMA_ID
WHERE t.is_ms_shipped=0 and type_desc = 'USER_TABLE'
ORDER BY s.NAME, t.NAME

Resources