I want to query the name of all columns of a table. I found how to do this in:
But I also need to know:
Just run this command
EXEC sp_columns 'Your Table Name'
SELECT TOP (0) [toID]
,[sourceID]
,[name]
,[address]
FROM [ReportDatabase].[Ticket].[To]
Simple and doesnt require any sys tables
You can try this.This gives all the column names with their respective data types.
desc <TABLE NAME> ;
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:
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.
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 ;