Column Names from SQL Server - sql

I am trying without success to get column names of my table in SQL Server.
I have tried the following:
SELECT * FROM [myDB].INFORMATION_SCHEMA.COLUMNS where [TABLE_NAME] = N'myTable'
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='myTable'
SELECT COLUMN_NAME , *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTable' AND TABLE_SCHEMA='dbo'
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = (SELECT id FROM sysobjects WHERE [Name] = 'myTable')
SELECT c.name FROM sys.columns c
INNER JOIN sys.tables t
ON t.object_id = c.object_id
AND t.name = 'myTable'
What is being returned is, what I think is, meta data of the table.
While in fact the actual column names are:
How can I return the column names from 'myTable'?

This solution returned the list I was looking for
SELECT name
FROM sys.columns
WHERE object_id = Object_id('myTable')

Related

Is there any way to iterate through each column in a table in SQL Server

I have a table with 10 columns.What i need is to select each column through while loop(select each column name not each column values) and find if its name ends with 'box' if it is yes then add that column value to a variable.
For eg:
while(column_name(1) = like'%box')
begin
select #value = column_name from table
select column_name = column_name + 1 (i.e select next column name from table)
end
Not done with a while loop but a quick and easy way to find any column where the name like.
SELECT
c.name AS 'ColumnName'
,t.name AS 'TableName'
FROM
sys.columns c
JOIN
sys.tables t ON c.object_id = t.object_id
WHERE
t.name = 'TableName'
AND c.name LIKE 'box%'
ORDER BY
TableName
,ColumnName;
Answer updated to now include the table name in the where clause.

Fetch Column Name from Table

I have 2 Requirements:
I want to write a SQL Command to fetch the Column Names from a Participant Table where the Column Name must be matching the word %Track%.
I want to fetch all the Table Name in the Database where it contains Column Name LIKE %Track%
"USER_TAB_COLUMNS" Does not run but gives error. Invalid object name 'USER_TAB_COLUMNS'.
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = (SELECT id FROM sysobjects WHERE type = 'V' AND [Name] = 'Participant')
Runs but there is no record fetched by this query.
Please suggest me the Query which will give me the desired resultant.
I want to fetch all the Table Name in the Database where it contains Column Name LIKE %Track%
You can try this
SELECT c.name AS ColumnName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%Track%'
I want to write a SQL Command to fetch the Column Names from a Participant Table where the Column Name must be matching the word %Track%
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Participant' and column_name like '%Track%'
And if you want to find in all the tables the
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name like '%Track%'
select * from sys.columns
where name like '%your wild card%'
and object_id = object_id('tablename')
try this
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
COLUMN_NAME = 'Your column name'
Try to use INFORMATION_SCHEMA.COLUMNS. It might help you. The query would be like:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Participant'

Find references to one database's columns in all other databases

I want these 5 columns as output when a stored procedure, in any database on the server, references a column in a specific database (let's say the database is AA).
Column_name Table_Name Schema_Name Procedure_Name Database_Name
Four of the columns are really easy to get - for the current database that you're in:
SELECT
TableName = t.Name,
SchemaName = s.Name,
ColumnName = c.Name,
DatabaseName = DB_NAME()
FROM
sys.tables t
INNER JOIN
sys.schemas s ON [t].[schema_id] = [s].[schema_id]
INNER JOIN
sys.columns c ON [t].[object_id] = [c].[object_id]
What you cannot get easily is all columns across all tables in all databases. Also: determining in which procedure each column is used is also rather tricky (or next to impossible).
From marc_s answer i generate a query which gives comma separated Procedure_Name depended by that table
SELECT
TableName = t.Name,
SchemaName = s.Name,
ColumnName = c.Name,
DatabaseName = DB_NAME(),
STUFF((SELECT ',' + name
FROM sys.procedures
WHERE object_id in (SELECT distinct id from sys.sysdepends
WHERE depid = (SELECT object_id FROM sys.tables
WHERE name=t.Name)
)
FOR XML PATH('')), 1, 0, '') AS sps
FROM
sys.tables t
INNER JOIN
sys.schemas s ON [t].[schema_id] = [s].[schema_id]
INNER JOIN
sys.columns c ON [t].[object_id] = [c].[object_id]

SQL Server: Return list of columns shared by a group of database tables

I'm inheriting a large report that we would like to automate. I believe most of the data is in a data warehouse that I can access through SQL Server. The issue I have is that I do not have a lot of documentation (data dictionary, schema, etc.) and I want to determine which fields are common among several tables. Normally, when I want to return a list of tables and columns, I would query the information schema. However, in this case, I'm basically looking for a query that is something like:
select table_name, column_name
from (information_schema, others?)
where table_name like 'T_Blah %'
and column_names are equal
I realize I can get to this through the object browser, but once I start getting into a larger number of tables, I would like a quick query-based approach to identifying my fields for joining.
I appreciate any help I can get. I googled this for a while, but I didn't find a solution (or I was oblivious to the fact that I had found one).
As well as information schema you also have the system table syscolumns. Assuming you use the former, something like this should work:
select column_name, count(distinct table_name)
from information_schema.columns
group by column_name
having count(distinct table_name) > 1
Obviously you could restrict by table name/schema if you wanted to look at a subset
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
If I understood yo correctly, you can try this:
SELECT TABLE_NAME, COLUMN_NAME
FROM ( SELECT *, COUNT(*) OVER(PARTITION BY COLUMN_NAME) Quant
FROM INFORMATION_SCHEMA.COLUMNS) A
WHERE TABLE_NAME LIKE 'T_Blah%' AND Quant > 1
ORDER BY COLUMN_NAME, TABLE_NAME
This should work for sql-server. This is just a query I keep on hand, so it is a little more than you requested. But, I kept it in case you want the extra info :). Just remove it if not.
select distinct columns.name, schemas.name + '.' + tables.name
from sys.columns
join sys.tables
on tables.object_id = columns.object_id
join sys.schemas
on schemas.schema_id = tables.schema_id
where tables.name like '%blah%'
order by columns.name, schemas.name + '.' + tables.name
This will yield the column names and data types in a specified table that also appear in other tables followed by a comma separated list of tables in which they appear:
SELECT COLUMN_NAME, DATA_TYPE, REPLACE(REPLACE(REPLACE(
(SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (COLUMN_NAME = CommonColumns.COLUMN_NAME) AND (DATA_TYPE = CommonColumns.DATA_TYPE)
FOR XML PATH(''))
, '</TABLE_NAME><TABLE_NAME>', ', '), '<TABLE_NAME>', ''), '</TABLE_NAME>', '')
AS Tables
FROM (SELECT DISTINCT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'T_Blah%') AS CommonColumns
WHERE (SELECT COUNT(TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (COLUMN_NAME = CommonColumns.COLUMN_NAME) AND (DATA_TYPE = CommonColumns.DATA_TYPE)) > 1
To have it do this for all tables, simply remove the WHERE TABLE_NAME LIKE 'T_Blah%'.
Or as Aaron recommends, avoid INFORMATION_SCHEMA:
SELECT ColumnName, sys.types.name AS DataType, REPLACE(REPLACE(REPLACE(
(SELECT sys.tables.name AS TableName
FROM sys.columns INNER JOIN
sys.tables ON sys.columns.object_id = sys.tables.object_id
WHERE (sys.tables.type = 'U') AND (sys.columns.name = CommonColumns.ColumnName) AND
(sys.columns.system_type_id = CommonColumns.system_type_id)
FOR XML PATH(''))
, '</TableName><TableName>', ', '), '<TableName>', ''), '</TableName>', '')
AS Tables
FROM (SELECT DISTINCT sys.columns.name AS ColumnName, sys.columns.system_type_id
FROM sys.columns INNER JOIN
sys.tables ON sys.columns.object_id = sys.tables.object_id
WHERE (sys.tables.type = 'U') AND (sys.tables.name LIKE 'T_Blah%')) AS CommonColumns INNER JOIN
sys.types ON sys.types.system_type_id = CommonColumns.system_type_id
WHERE ((SELECT COUNT(sys.tables.object_id) AS TableCount
FROM sys.columns INNER JOIN
sys.tables ON sys.columns.object_id = sys.tables.object_id
WHERE (sys.tables.type = 'U') AND (sys.columns.name = CommonColumns.ColumnName) AND
(sys.columns.system_type_id = CommonColumns.system_type_id)) > 1)
ORDER BY CommonColumns.ColumnName, sys.types.name
To get relations by foreign keys use:
SELECT sys.foreign_keys.name AS ForeignKeyName, OBJECT_NAME(sys.foreign_key_columns.parent_object_id) AS ForeignKeyTableName,
ForeignKeyColumns.name AS ForeignKeyColumnName, OBJECT_NAME(sys.foreign_key_columns.referenced_object_id) AS ReferencedTableName,
ReferencedColumns.name AS ReferencedColumnName
FROM sys.foreign_keys INNER JOIN
sys.foreign_key_columns ON sys.foreign_keys.object_id = sys.foreign_key_columns.constraint_object_id INNER JOIN
sys.columns AS ForeignKeyColumns ON sys.foreign_key_columns.parent_object_id = ForeignKeyColumns.object_id AND
sys.foreign_key_columns.parent_column_id = ForeignKeyColumns.column_id INNER JOIN
sys.columns AS ReferencedColumns ON sys.foreign_key_columns.referenced_object_id = ReferencedColumns.object_id AND
sys.foreign_key_columns.referenced_column_id = ReferencedColumns.column_id
WHERE (OBJECT_NAME(sys.foreign_key_columns.parent_object_id) LIKE 'T_Blah%') OR (OBJECT_NAME(sys.foreign_key_columns.referenced_object_id)
LIKE 'T_Blah%')

SQL Server: Get table primary key using sql query [duplicate]

This question already has answers here:
How do you list the primary key of a SQL Server table?
(28 answers)
Closed 3 years ago.
I want to get a particular table's primary key using SQL query for SQL Server database.
In MySQL I am using following query to get table primary key:
SHOW KEYS FROM tablename WHERE Key_name = 'PRIMARY'
What is equivalent of above query for SQL Server ?.
If There is a query that will work for both MySQL and SQL Server then It will be an ideal case.
I also found another one for SQL Server:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema'
Found another one:
SELECT
KU.table_name as TABLENAME
,column_name as PRIMARYKEYCOLUMN
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
AND KU.table_name='YourTableName'
ORDER BY
KU.TABLE_NAME
,KU.ORDINAL_POSITION
;
I have tested this on SQL Server 2003/2005
Using SQL SERVER 2005, you can try
SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i INNER JOIN
sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
Found at SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database
From memory, it's either this
SELECT * FROM sys.objects
WHERE type = 'PK'
AND object_id = OBJECT_ID ('tableName')
or this..
SELECT * FROM sys.objects
WHERE type = 'PK'
AND parent_object_id = OBJECT_ID ('tableName')
I think one of them should probably work depending on how the data is stored
but I am afraid I have no access to SQL to actually verify the same.
SELECT COLUMN_NAME FROM {DATABASENAME}.INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME LIKE '{TABLENAME}' AND CONSTRAINT_NAME LIKE 'PK%'
WHERE
{DATABASENAME} = your database from your server AND
{TABLENAME} = your table name from which you want to see the primary key.
NOTE : enter your database name and table name without brackets.
select *
from sysobjects
where xtype='pk' and
parent_obj in (select id from sysobjects where name='tablename')
this will work in sql 2005
The code I'll give you works and retrieves not only keys, but a lot of data from a table in SQL Server. Is tested in SQL Server 2k5/2k8, dunno about 2k. Enjoy!
SELECT DISTINCT
sys.tables.object_id AS TableId,
sys.columns.column_id AS ColumnId,
sys.columns.name AS ColumnName,
sys.types.name AS TypeName,
sys.columns.precision AS NumericPrecision,
sys.columns.scale AS NumericScale,
sys.columns.is_nullable AS IsNullable,
( SELECT
COUNT(column_name)
FROM
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
WHERE
TABLE_NAME = sys.tables.name AND
CONSTRAINT_NAME =
( SELECT
constraint_name
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
TABLE_NAME = sys.tables.name AND
constraint_type = 'PRIMARY KEY' AND
COLUMN_NAME = sys.columns.name
)
) AS IsPrimaryKey,
sys.columns.max_length / 2 AS CharMaxLength /*BUG*/
FROM
sys.columns, sys.types, sys.tables
WHERE
sys.tables.object_id = sys.columns.object_id AND
sys.types.system_type_id = sys.columns.system_type_id AND
sys.types.user_type_id = sys.columns.user_type_id AND
sys.tables.name = 'TABLE'
ORDER BY
IsPrimaryKey
You can use only the primary key part, but I think that the rest might become handy.
Best regards,
David
This should list all the constraints and at the end you can put your filters
/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME)
AS
(
SELECT CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME='' ,
REFERENCE_COL_NAME=''
FROM sys.key_constraints as PKnUKEY
INNER JOIN sys.tables as PKnUTable
ON PKnUTable.object_id = PKnUKEY.parent_object_id
INNER JOIN sys.index_columns as PKnUColIdx
ON PKnUColIdx.object_id = PKnUTable.object_id
AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
INNER JOIN sys.columns as PKnUKEYCol
ON PKnUKEYCol.object_id = PKnUTable.object_id
AND PKnUKEYCol.column_id = PKnUColIdx.column_id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=PKnUTable.name
AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE='FK',
PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30))
FROM sys.foreign_key_columns FKC
INNER JOIN sys.sysobjects oConstraint
ON FKC.constraint_object_id=oConstraint.id
INNER JOIN sys.sysobjects oParent
ON FKC.parent_object_id=oParent.id
INNER JOIN sys.all_columns oParentCol
ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
INNER JOIN sys.sysobjects oReference
ON FKC.referenced_object_id=oReference.id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=oParent.name
AND oParentColDtl.COLUMN_NAME=oParentCol.name
INNER JOIN sys.all_columns oReferenceCol
ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
)
select * from ALL_KEYS_IN_TABLE
where
PARENT_TABLE_NAME in ('YOUR_TABLE_NAME')
or REFERENCE_TABLE_NAME in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;
For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx
Keep in mind that if you want to get exact primary field you need to put TABLE_NAME and TABLE_SCHEMA into the condition.
this solution should work:
select COLUMN_NAME from information_schema.KEY_COLUMN_USAGE
where CONSTRAINT_NAME='PRIMARY' AND TABLE_NAME='TABLENAME'
AND TABLE_SCHEMA='DATABASENAME'
It is also (Transact-SQL) ... according to BOL.
-- exec sp_serveroption 'SERVER NAME', 'data access', 'true' --execute once
EXEC sp_primarykeys #table_server = N'server_name',
#table_name = N'table_name',
#table_catalog = N'db_name',
#table_schema = N'schema_name'; --frequently 'dbo'