Fetch Column Name from Table - sql

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'

Related

Can I find remaining 85-90 columns which was not provided to me? in databricks [duplicate]

I want to query the name of all columns of a table. I found how to do this in:
Oracle
MySQL
PostgreSQL
But I also need to know: how can this be done in Microsoft SQL Server (2008 in my case)?
You can obtain this information and much, much more by querying the Information Schema views.
This sample query:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
Can be made over all these DB objects:
CHECK_CONSTRAINTS
COLUMN_DOMAIN_USAGE
COLUMN_PRIVILEGES
COLUMNS
CONSTRAINT_COLUMN_USAGE
CONSTRAINT_TABLE_USAGE
DOMAIN_CONSTRAINTS
DOMAINS
KEY_COLUMN_USAGE
PARAMETERS
REFERENTIAL_CONSTRAINTS
ROUTINES
ROUTINE_COLUMNS
SCHEMATA
TABLE_CONSTRAINTS
TABLE_PRIVILEGES
TABLES
VIEW_COLUMN_USAGE
VIEW_TABLE_USAGE
VIEWS
You can use the stored procedure sp_columns which would return information pertaining to all columns for a given table. More info can be found here http://msdn.microsoft.com/en-us/library/ms176077.aspx
You can also do it by a SQL query. Some thing like this should help:
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo.yourTableName')
Or a variation would be:
SELECT o.Name, c.Name
FROM sys.columns c
JOIN sys.objects o ON o.object_id = c.object_id
WHERE o.type = 'U'
ORDER BY o.Name, c.Name
This gets all columns from all tables, ordered by table name and then on column name.
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
This is better than getting from sys.columns because it shows DATA_TYPE directly.
You can use sp_help in SQL Server 2008.
sp_help <table_name>;
Keyboard shortcut for the above command: select table name (i.e highlight it) and press ALT+F1.
By using this query you get the answer:
select Column_name
from Information_schema.columns
where Table_name like 'table name'
You can write this query to get column name and all details without using
INFORMATION_SCHEMA in MySql :
SHOW COLUMNS FROM database_Name.table_name;
SELECT name
FROM sys.columns
WHERE object_id = OBJECT_ID('TABLE_NAME')
TABLE_NAME is your table
--This is another variation used to document a large database for conversion (Edited to --remove static columns)
SELECT o.Name as Table_Name
, c.Name as Field_Name
, t.Name as Data_Type
, t.length as Length_Size
, t.prec as Precision_
FROM syscolumns c
INNER JOIN sysobjects o ON o.id = c.id
LEFT JOIN systypes t on t.xtype = c.xtype
WHERE o.type = 'U'
ORDER BY o.Name, c.Name
--In the left join, c.type is replaced by c.xtype to get varchar types
You can try this.This gives all the column names with their respective data types.
desc <TABLE NAME> ;
SELECT column_name, data_type, character_maximum_length, table_name,ordinal_position, is_nullable
FROM information_schema.COLUMNS WHERE table_name LIKE 'YOUR_TABLE_NAME'
ORDER BY ordinal_position
Just run this command
EXEC sp_columns 'Your Table Name'
Summarizing the Answers
I can see many different answers and ways to do this but there is the rub in this and that is the objective.
Yes, the objective. If you want to only know the column names you can use
SELECT * FROM my_table WHERE 1=0
or
SELECT TOP 0 * FROM my_table
But if you want to use those columns somewhere or simply say manipulate them then the quick queries above are not going to be of any use. You need to use
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'Customers'
one more way to know some specific columns where we are in need of some similar columns
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME like N'%[ColumnName]%' and TABLE_NAME = N'[TableName]'
This SO question is missing the following approach :
-- List down all columns of table 'Logging'
select * from sys.all_columns where object_id = OBJECT_ID('Logging')
You can try using :-
USE db_name;
DESCRIBE table_name;
it'll give you column names with the type.
It will check whether the given the table is Base Table.
SELECT
T.TABLE_NAME AS 'TABLE NAME',
C.COLUMN_NAME AS 'COLUMN NAME'
FROM INFORMATION_SCHEMA.TABLES T
INNER JOIN INFORMATION_SCHEMA.COLUMNS C ON T.TABLE_NAME=C.TABLE_NAME
WHERE T.TABLE_TYPE='BASE TABLE'
AND T.TABLE_NAME LIKE 'Your Table Name'
In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS.
Here is the code:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='YourTableName'
you can use this query
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME like N'%[ColumnName]%' and TABLE_NAME = N'[TableName]'
SELECT c.Name
FROM sys.columns c
JOIN sys.objects o ON o.object_id = c.object_id
WHERE o.object_id = OBJECT_ID('TABLE_NAME')
ORDER BY c.Name
One other option which is arguably more intuitive is:
SELECT [name]
FROM sys.columns
WHERE object_id = OBJECT_ID('[yourSchemaType].[yourTableName]')
This gives you all your column names in a single column.
If you care about other metadata, you can change edit the SELECT STATEMENT TO SELECT *.
SELECT TOP (0) [toID]
,[sourceID]
,[name]
,[address]
FROM [ReportDatabase].[Ticket].[To]
Simple and doesnt require any sys tables
Simple and doesn't require sys variables:
SHOW COLUMNS FROM suppliers;
Some SQL Generating SQL:
DROP TABLE IF EXISTS test;
CREATE TABLE test (
col001 INTEGER
, col002 INTEGER
, col003 INTEGER
, col004 INTEGER
, col005 INTEGER
, col006 INTEGER
, col007 INTEGER
, col008 INTEGER
, col009 INTEGER
, col010 INTEGER
)
;
INSERT INTO test(col001) VALUES(1);
INSERT INTO test(col002) VALUES(1);
INSERT INTO test(col005) VALUES(1);
INSERT INTO test(col009) VALUES(1);
INSERT INTO test VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
SELECT
CASE ROW_NUMBER() OVER(ORDER BY ordinal_position)
WHEN 1 THEN
'SELECT'+CHAR(10)+' *'+CHAR(10)+'FROM test'
+CHAR(10)+'WHERE '
ELSE
' OR '
END
+ column_name +' IS NOT NULL'
+ CASE ROW_NUMBER() OVER(ORDER BY ordinal_position DESC)
WHEN 1 THEN
CHAR(10)+';'
ELSE
''
END
FROM information_schema.columns
WHERE table_schema='dbo'
AND table_name = 'test'
ORDER BY
ordinal_position;
-- the whole scenario. Works for 10 , will work for 100, too:
-- out -----------------------------------------------
-- out SELECT
-- out *
-- out FROM test
-- out WHERE col001 IS NOT NULL
-- out OR col002 IS NOT NULL
-- out OR col003 IS NOT NULL
-- out OR col004 IS NOT NULL
-- out OR col005 IS NOT NULL
-- out OR col006 IS NOT NULL
-- out OR col007 IS NOT NULL
-- out OR col008 IS NOT NULL
-- out OR col009 IS NOT NULL
-- out OR col010 IS NOT NULL
-- out ;

How do I delete Columns from a table if not another table using SQL?

Let's say
Table1 has columns: Column1 Column2 Column3
Table2 has columns: Column2 Column3 Column4
I want Column1 to be deleted because it's not in Table2.
I am guessing I need to a JOIN and then delete from that. I did some searching and found this article:
How can I get column names from a table in SQL Server?
I tried:
SELECT T.TABLE_NAME AS 'TABLE NAME',
C.COLUMN_NAME AS 'COLUMN NAME'
FROM INFORMATION_SCHEMA.TABLES T
INNER JOIN INFORMATION_SCHEMA.COLUMNS C ON
T.TABLE_NAME=C.TABLE_NAME
WHERE T.TABLE_TYPE='BASE TABLE'
AND T.TABLE_NAME LIKE 'T'
but I can only get the Column names to show for one Table. I tried modifying it with no luck, and of course I need to delete as well. Even if I could get a list of columns that don't match would help. I am no SQL expert but that's as far as I got. Any help would be appreciated. Thanks!
I've made a simple query that checks what column names both tables are containing and then counts the number of occurences of each name. It then shows the columns that appear less than two times i.e. the ones that only appears in one of the two tables.
select name from (
select [object_id], name from sys.all_columns where [object_id] = (select [object_id] from sys.tables where name = 'Table1')
UNION ALL
select [object_id], name from sys.all_columns where [object_id] = (select [object_id] from sys.tables where name = 'Table2')
) o
group by o.name
having count([object_id]) < 2
You can use the data from this table to make a separate "drop column" query.
You need a dynamic query in this case because you build your drop statement while you are running the select statement to get the column name.
declare #column varchar(max)
set #column = (select............)
-- Print #column -- Use this to check if the column name is what you want
declare #sql nvarchar(max)
set #sql = 'alter table Table1 drop column ' + #column
execute (#sql)
Let me know if you have any questions.

How to use the dynamic column name from the table in a where clause

I am trying to get the dynamic column names from the table using the 'INFORMATION_SCHEMA.COLUMNS' Following is the query.
Select COLUMN_NAME into #TempTable
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'MyTable'
Result:
COLUMN_NAME
Person_ID
Person_Name
Person_Address
Wanting to Do:
Select * from MyTable where Person_ID = 1
What can be the ways to use the Person_ID from 1st query to the second query?
You can use dynamic SQL to execute this via the EXEC command.
Build a VARCHAR string for your query based on the dynamic column names you are getting from your first query, then EXEC on the string you have created.
You have not provided enough information on exactly what columns you need in your WHERE clause, or how you determine which ones, but dynamic SQL seems to be what you need here.
if you are trying to do something like this
select * from [table] where [col] =#param
then you can use query like below
declare #query nvarchar(max)
select
#query='select * from '+t.name +
' where '+c.name + ' ='+
case
when c.name ='Person_ID' then '1'
when c.name ='Someother_ID' then '10'
else c.name
end
from sys.tables t join sys.columns c
on c.object_id=t.object_id
and t.name ='MyTable'
exec( #query)

Column Names from SQL Server

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')

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.