Is it possible for an SQL table to have zero columns? - sql

I'm using the following query to gather information about a table's columns:
SELECT COLUMN_NAME,
ORDINAL_POSITION,
DATA_TYPE,
CHARACTER_MAXIMUM_LENGTH,
Is_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableName'
ORDER BY ORDINAL_POSITION
If this query returns zero results, can I safety declare that the table doesn't exist? Or is is somehow possible that the table exists but (perversely) has no columns?
I'm already querying INFORMATION_SCHEMA.TABLES to find out if the table exists, but I'd like to cut it down to one query if possible.
For future reference, I found these related questions:
Create a table without columns
Can I select 0 columns in SQL Server?

If you try:
create table TestTable (id int)
alter table TestTable drop column id
SQL Server complains that:
Msg 4923, Level 16, State 1, Line 1
ALTER TABLE DROP COLUMN failed because 'id' is the only data column in table
'TestTable'. A table must have at least one data column.
So a table must always have at least one column.

If you were to look at the definition for the INFORMATION_SCHEMA.COLUMNS view, you'd see that it starts with the sys.objects table, looking for types of 'U' (Table, user-defined) or 'V' (view), so it is already performing the check for table existence for you.
CREATE VIEW INFORMATION_SCHEMA.COLUMNS
AS
SELECT
...
FROM
sys.objects o JOIN sys.columns c ON c.object_id = o.object_id
LEFT JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE
o.type IN ('U', 'V')

Related

How do I add/remove columns using SQL Server 2012 Management Studio

When I execute
exec sp_columns TABLE_NAME
it returns many columns, I need to display specific columns only and add a description column as well.
Is there anyway for me to customize the table to do this?
I am using SQL Server 2012 Management Studio
With SSMS you can use the table designer to add columns fairly easily. In the server browser, find your table, right click, and "Design."
--Check if column does not exists, if yes than add.
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE [name] = N'Column_Name'
AND [object_id] = OBJECT_ID(N'Table_Name')
)
BEGIN
ALTER TABLE Table_Name ADD Column_Name Type;
END
-- Similarly for removing column
--Check if column does exists, if yes than add.
IF EXISTS (
SELECT *
FROM sys.columns
WHERE [name] = N'Column_Name'
AND [object_id] = OBJECT_ID(N'Table_Name')
)
BEGIN
ALTER TABLE Table_Name Remove Column_Name;
END
GO
select column_name, table_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME like '%table name%' and column_name
in
(
'column1',
'column2'
)

Insert column names into stored procedure SELECT statement from separate table

I am trying to figure out the best method to insert column names held in Table1 into a SELECT statement running against Table2. This query is running in a stored procedure. That doesn't do a very good job of explaining, so lets say I had these values in Table1:
What I am trying to do is use these column names in the SELECT statement against Table2:
Select -- Column Names
from Table2
where UserId = 3;
I'm not sure if an input parameter could be used in that way or how to pass the values into it. For example:
Select #ColumnNames
from Table2
where UserId = 3;
Or maybe a join to table 2?
Thanks!
You will have to use Dynamic SQL
declare #columns varchar(1000)
declare #sql varchar(8000)
select #columns='', #sql=''
select #columns=#columns+value+',' from table1
set #columns=left(#columns,len(#columns)-1)
set #sql='select '+#columns+' from table2'
exec(#sql)
But beware of SQL Injection and read www.sommarskog.se/dynamic_sql.html
You could query the system tables to get the column(s) i.e. (take out WHERE clause to see all the tables and columns)
SELECT tab.name AS TableName,
col.name AS ColName,
tp.name AS SType,
col.max_length,
col.[precision],
(CASE col.is_nullable
WHEN 1 THEN 'true'
WHEN 0 THEN 'false'
ELSE 'unknown'
END) AS Is_Nullable
FROM sys.tables as tab
LEFT OUTER JOIN sys.columns AS col
ON tab.object_id = col.object_id
LEFT OUTER JOIN sys.types AS tp
ON col.system_type_id = tp.system_type_id
WHERE tab.name = 'Table1'
ORDER BY tab.name,col.name

SQL query for finding all tables ROWS with two columns in them

I have a DataBase with around +100 tables, like half of tables have column A & column B.
My question is, Can I query all tables that have this columns with a specific values e.g.
SELECT * FROM DATABASE
WHERE
EACHTABLE HAS COLUMN A = 21 //only if table has columns and then values
AND
COLUMN B = 13
I am not sure how exact I will do it, nothing is coming up on google either
You can use the undocumented MS stored procedure sp_MSforeachtable, if you fancy living life recklessly:
create table T1 (
ColumnA int not null,
ColumnB int not null
)
go
create table T2 (
ColumnA int not null,
Column2 int not null
)
go
create table T3 (
Column1 int not null,
ColumnB int not null
)
go
create table T4 (
ColumnA int not null,
ColumnB int not null
)
go
insert into T1 values (1,2);
insert into T2 values (3,4);
insert into T3 values (5,6);
insert into T4 values (7,8);
go
create table #Results (TableName sysname,ColumnA int,ColumnB int)
exec sp_MSforeachtable 'insert into #Results select ''?'',ColumnA,ColumnB from ?',
#whereand = ' and syso.object_id in (select object_id from sys.columns where name=''ColumnA'') and syso.object_id in (select object_id from sys.columns where name=''ColumnB'')'
select * from #Results
drop table #Results
Result:
TableName ColumnA ColumnB
------------------------------------- ----------- -----------
[dbo].[T1] 1 2
[dbo].[T4] 7 8
By default, sp_MSforeachtable will, as its name implies, perform the same task for each table in the database. However, one optional parameter to this procedure, called #Whereand, can be used to modify the WHERE clause of the internal query that enumerates the tables in the database. It helps to know that this internal query has already established two aliases to some of the system views. o is an alias for sysobjects (the legacy system view). syso is an alias for sys.all_objects (a more modern system view).
Once sp_MSforeachtable has decided which tables to run against, it will execute the query given to it as its first parameter. But, it will replace ? with the schema and table name (? is the default replacement character. This can be changed as needed)
In this case, I chose to create a temp table, then have each selected table store its results into this temp table, and after sp_MSforeachtable has finished running, to select the combined results out with no further processing.
There is a similar (and similarly undocumented) procedure called sp_MSforeachdb which will access each user database on the server. These can even be combined (although you have to be careful with doubling up ' quote characters twice, at times). However, there's no equivalent sp_MSforeachcolumn.
Try this:
select t.name from sys.objects t inner join sys.columns c
on t.name=OBJECT_NAME(c.object_id)
where t.type='U'
and c.name in('col1','col2')
group by t.name
having COUNT(*) = 2
order by 1
Then you just loop through all the tables and fine the values for these columns.
Like
Declare #out TABLE(tblname varchar(100))
if exists(select * from tbl1 where col1='21' and col2='22')
BEGIN
INSERT INTO #out
select tbl1
END
You can try like this using dynamic query.
select 'select * from '+table_name+ ' where'+column_name+'=21'
from information_schema.columns where column_name = 'A'
I suggest to use two steps:
First, find out all tables in your database that have these two columns and use it for a temporal derived table. For I am not an expert in SQL-Server 2008 I recommend to have a look at the whitepages.
The expression might look like this:
SELECT tablename
FROM information_schema.tables sdbt
WHERE "column a" IN
(SELECT columns
FROM information_schema.columns col
WHERE col.tablename = sdbt.tablename)
Second, use a expresssion to filter the results according to your demanded values.
This command should do the trick in one go, only for column A, amend accordingly to include any other columns you need:
exec sp_MSforeachtable
#command1=N'SELECT * FROM ? WHERE A = 21',
#whereand=' and o.name IN (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = ''A'') '

Drop table if exist with similar name in two schema

I use this command to drop a table in sql-server 2008
IF EXISTS(SELECT name FROM [DBName]..sysobjects WHERE name = N'TableName' AND xtype='U')
DROP TABLE [DBName].[SchemaName].[TableName];
But now I have 2 tables with same name in different schema:
[DBName].[Schema1].[Members]
And
[DBName].[Schema2].[Members]
So, what is your suggestion for check if exist this tables? How can I check table names with schema?
UPDATE:
OK, there is 3 different answers and all of them worked, so I don't know which one is better, does any one know about use object_id or sys.tables?
IF EXISTS(
SELECT *
FROM [DBName].sys.tables t
JOIN [DBName].sys.schemas s
ON t.SCHEMA_ID = s.schema_id
WHERE
t.name = N'TableName' AND t.type='U'
AND s.NAME = 'SchemaName'
)
DROP TABLE [DBName].[SchemaName].[TableName];
Update:
object_id in sys.tables is the same as object_id in sysobjects for the same table. And is completely the same as function OBJECT_ID returns for the same table name. See the following illustrating examples.
So, you may simplify the query:
IF exists
(
SELECT *
FROM DBName.sys.tables
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND type = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
or in this way:
IF exists
(
SELECT *
FROM DBName.sys.objects
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND type = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
or for sql2000-styled tables:
IF exists
(
SELECT *
FROM DBName..sysobjects
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND xtype = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
Use this:
IF EXISTS
(
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[DBName].[Schema1].[Member]')
AND type in (N'U')
)
PRINT 'Yes'
ELSE
PRINT 'No';
Don't use sysobjects. Use the modern system views in the sys schema (introduced in 2005):
select * from sys.tables
where
schema_id = SCHEMA_ID('Schema1') and
name='tablename'
As soon as you have one "modern" schema in a 2005 or later database, you cannot reliably use sysobjects to match with schemas. If you only have "old" schemas (objects belonging to users and roles), you may be able to query based on user_id.
Wouldn't it be simplest just to:
IF object_id('[schema].[table]') > 0
DROP TABLE [schema].[table]
For non existent tables object_id() returns NULL
For some system tables it returns a negative int

How to identify whether the table has identity column

I want to find out whether the table has an identity column or not. Table is unknown to me. I have not done the structure of the table. Using Query?
I am using Sql Server Compact Edition.
IF (OBJECTPROPERTY(OBJECT_ID('TABLE_NAME'), 'TableHasIdentity') = 1)
ObjectProperty is available starting sql server 2008 Reference:
OBJECTPROPERTY
This query returns a table's identity column name:
CREATE PROCEDURE dbo.usp_GetIdentity
#schemaname nvarchar(128) = 'dbo'
,#tablename nvarchar(128)
AS
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) AS TABLENAME,
NAME AS COLUMNNAME,
SEED_VALUE,
INCREMENT_VALUE,
LAST_VALUE,
IS_NOT_FOR_REPLICATION
FROM SYS.IDENTITY_COLUMNS
WHERE OBJECT_NAME(OBJECT_ID) = #tablename
AND OBJECT_SCHEMA_NAME(object_id) = #schemaname
END
Then form the code side.
Call this stored procedure using the datareader role, then check datareader.hasrows(). If the condition value is true (1), then the table has identity column if set. If not then it doesn't have an identity column.
I know it's long time ago but i found this helpful
try this :
IF EXISTS (SELECT * from syscolumns where id = Object_ID(#TABLE_NAME) and colstat & 1 = 1)
BEGIN
-- Do your things
END
Any of the below queries can be used to check if an Identity Column is present in the table
1)
SELECT *
FROM sys.identity_columns
WHERE OBJECT_NAME(object_id) = 'TableName'
2)
SELECT *
FROM sys.identity_columns
WHERE object_id = (
SELECT id
FROM sysobjects
WHERE name = 'TableName'
)
I would just like to add this option as well as I think it is the simplest
SELECT COLUMNPROPERTY(OBJECT_ID('TableName'),'ColumnName','isidentity')
One way to do this would be to make use of the stored procedure sp_help. I.e:
sp_help MyTable
This will return a DataSet that has all the information you would need on the table. There is a specific Table that has information on identities.
I.e:
If it does not contain an identity field, the Identity column will say: "No identity column defined".
#Pranay: he said Compact Edition. Stored procedures aren't supported, and there is no sys.anything.
This is the call:
SELECT Count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE AUTOINC_INCREMENT IS NOT NULL AND TABLE_NAME='this_table'
It will return either 1 (true) or 0 (false).
...
declare #tblhasIdentCol bit = IF (IDENT_CURRENT( #dbName +'.'+ #schemaName +'.'+ #tableName ) IS NOT NULL , 1 , 0 )
You get numeric value if table has identity
Very simple answer would be to run this:
SELECT IDENT_CURRENT('TABLE-NAME')
This would give max value of identity column if exists, if the column doesn't exist, it gives 1 as result.
Based on max value, you can identify which column is having that and determine the identity column.
This the query that get u all the tableNames, columnnames of the table, and is_identity or not in the selected database
SELECT
sys.columns.name
, sys.tables.name
, is_identity
FROM sys.columns
INNER JOIN sys.tables ON sys.tables.object_id = sys.columns.object_id
AND sys.columns.is_identity = 1
CREATE FUNCTION dbo.fnTableHasIdentity(#Tbl sysname)
RETURNS TINYINT
BEGIN
RETURN OBJECTPROPERTY(OBJECT_ID(#Tbl), 'TableHasIdentity')
END
--As simple as that!
select t.name as TableName,c.name as ColumnName
from sys.identity_columns c
inner join sys.tables t on c.object_id = t.object_id
where t.name = 'TableName'
If you like me, needed to be able to do this for tables in an arbitrary database, then I found the following solution:
IF EXISTS (
SELECT 1
FROM [database name].sys.identity_columns AS id_col
INNER JOIN [database name].sys.objects
ON objects.object_id = id_col.object_id
INNER JOIN [database name].sys.schemas
ON schemas.schema_id = objects.schema_id
AND schemas.name = 'schema name'
WHERE OBJECT_NAME(id_col.object_id, DB_ID('database name')) = 'table name'
) SELECT 1 ELSE SELECT 0
you can get the 1 or 0 Boolean Form if the current table has identity Columns by using this
SELECT Count(Column_ID) FROM sys.identity_columns WHERE OBJECT_NAME(object_id) = 'tableName'
One way to list all Tables with their identity column if it exists
to get you desired table add at the end of the filter "and o.name='TableName'"
where Tbale Nam is the table you are looking for
SELECT o.[Name][TableName],i.[name][IdentityColName] FROM
sys.objects o
left outer join sys.identity_columns i on i.object_id=o.object_id
where o.type='U'