75 columns in a table - I want to query only the first 25 columns in that table without naming each column name.... can you assist with a SQL query....
I been playing with the following:
Select Table_Name, Count(*) As ColumnCount
From Information_Schema.Columns
Group By Table_Name
Order By Table_Name
Doesn't meet my output........
If a Table has 75 columns, How can I see the first 25 columns without naming each column name? Don't want to delete Columns Only want to see the first 25 columns out of 75 columns in the same table.....TOP is not enable need another work around....
First 25 columns in a table query built into #query and then executed. Substitute correct #target_table value.
DECLARE
#target_table sysname
, #query nvarchar(max)
SET
#target_table = '_dimAreaOverlay'
; with of_interest as
(
SELECT
SS.name AS schemaname
, T.name AS tablename
, SC.name AS columname
FROM
sys.schemas SS
inner join
sys.tables T
ON T.schema_id = SS.schema_id
inner join
sys.columns SC
ON SC.object_id = T.object_id
WHERE
T.name = #target_table
AND SC.column_id < 26
)
, c AS
(
SELECT
STUFF((
SELECT
',' + QUOTENAME(I.columname)
FROM
of_interest I
FOR XML PATH('')), 1,1, '') AS column_list
, OI.tablename
, OI.schemaname
FROM
of_interest OI
GROUP BY
OI.schemaname
, OI.tablename
)
SELECT
#query = 'SELECT '
+ C.column_list
+ ' FROM '
+ QUOTENAME(C.schemaname)
+ '.'
+ QUOTENAME(C.tablename)
FROM C
EXECUTE(#query)
Find the table in Management Studio Object Explorer.
Right click it and choose Script Table As -> Select To -> New Query Editor Window
Delete unwanted columns.
Related
Today I have this query that returns all rows from all tables. But now I want to add a new column that would be the number of records in the last year. Most tables have a column called "DateInsert".
I have this:
SELECT
SCHEMA_NAME(t.[schema_id]) AS [SCHEMA],
OBJECT_NAME(p.[object_id]) AS [NOME_TABELA],
SUM(p.[rows]) AS [ROW_COUNT]
FROM [sys].[partitions] p
INNER JOIN [sys].[tables](NOLOCK) t ON p.[object_id] = t.[object_id]
WHERE p.[index_id] < 2
GROUP BY p.[object_id]
,t.[schema_id]
ORDER BY [ROW_COUNT] desc
How do i add a new column counting rows from the last year only?
Assuming, each table has DateInsert column. You can try using Dynamic SQL to prepare the count for each table from last year in one temporary table and then you can Join that temp table with your final query.
Something like this
Please note that, if any of your table dont have DateInsert Column, this query will fail. In order to look at list of tables, you can prepare the dynamic SQL for those tables only
DECLARE #SQLQuery NVARCHAR(MAX)
-- Preparing Dynamic SQL
SELECT #SQLQuery = STUFF(
(SELECT CONCAT('UNION SELECT ''', name ,''' AS [TableName], COUNT(1) AS [NoOfRowsFromLastYear] FROM ['
, name
, '] WITH (NOLOCK) WHERE YEAR(DateInsert) = (YEAR(GETDATE())-1)')
FROM [sys].[tables]
--WHERE name in ('TableName')
FOR XML PATH(''))
, 1, LEN('UNION '), ''
)
SELECT #SQLQuery = CONCAT('SELECT * INTO ##TableDetail FROM (', #SQLQuery, ') DataSet')
-- Check for table, if available, drop it
IF OBJECT_ID('tempdb..##TableDetail') IS NOT NULL DROP TABLE ##TableDetail;
-- Execute prepared query
EXECUTE sp_executesql #SQLQuery
-- Final Query with [ROW_COUNT_FROM_LAST_YEAR]
SELECT
SCHEMA_NAME(t.[schema_id]) AS [SCHEMA],
OBJECT_NAME(p.[object_id]) AS [NOME_TABELA],
SUM(p.[rows]) AS [ROW_COUNT],
td.NoOfRowsFromLastYear AS [ROW_COUNT_FROM_LAST_YEAR]
FROM [sys].[partitions] p
INNER JOIN [sys].[tables](NOLOCK) t ON p.[object_id] = t.[object_id]
INNER JOIN ##TableDetail td ON td.[TableName] = t.name
WHERE p.[index_id] < 2
GROUP BY p.[object_id]
,t.[schema_id]
,td.NoOfRowsFromLastYear
ORDER BY [ROW_COUNT] desc
I have around 200 tables. I want to create a view from all these tables. I feel it is inefficient to hardcode all the table names and do an UNION ALL in the view definition.
Instead I am planning to retrieve the table name from sysobjects table like
Select name from sysobjects where name like 'Warehouse_Inventory%'
How can I use these table names and create a view out of it?
Note: I am selecting only 10 columns which are common. If any column is not present in a table, I want to display NULL for it.
This Query may help you..
SELECT 'CREATE VIEW VIEW_NAME AS'
UNION ALL
SELECT 'SELECT * FROM ['+NAME+']
UNION ALL' FROM SYS.TABLES where name like 'Warehouse_Inventory%'
I am not sure why you want to use sys.sysojects instead of other sys views. Also now sure why when you want to union all tables you would want to search by a table name..... I would probably recommend a cursor on tables and temp tables to hold your results if you have 200 tables just do to size of the query but if you really really want to do it via union all here is a way...
Build a list of the 10 columns you want. Then run the query. you may need to tweak and add some cast/convert function to ensure everything is the right datatypes this can be done dynamically with sys.types and sys.columns or just make sure everything is a NVARCHAR(???) by altering my dynamic sql below and move forward.
DECLARE #ListOfColumns AS TABLE (ColumnName VARCHAR(100))
INSERT INTO #ListOfColumns (ColumnName) VALUES ('col1'),('col2'),('col3')
DECLARE #SQLStatement NVARCHAR(MAX)
;WITH cteColumnsTableCross AS (
SELECT
SchemaName = s.name
,t.schema_id
,TableName = t.name
,l.ColumnName
FROm
#ListOfColumns l
CROSS JOIN sys.tables t
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
)
, cteColumns AS (
SELECT
x.SchemaName
,x.TableName
,x.ColumnName
,ColumnExists = IIF(c.name IS NOT NULL,1,0)
,RowNum = ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY x.TableName DESC)
--you can add data type by getting from sys.columns and sys.types if desired
FROM
cteColumnsTableCross x
LEFT JOIN sys.tables t
ON x.TableName = t.name
AND x.schema_id = t.schema_id
LEFT JOIN sys.columns c
ON t.object_id = c.object_id
AND x.ColumnName = c.name
)
, cteSelectStatements AS (
SELECT
TableName = t.name
,TableSelect = 'SELECT TableName = ''' + t.name + ''', ' +
STUFF(
(SELECT ', ' + c.ColumnName + ' = ' + IIF(c.ColumnExists = 0,'NULL',c.ColumnName)
FROM
cteColumns c
WHERE t.name = c.Tablename
FOR XML PATH(''))
,1,1,'')
+ ' FROM ' + t.name +
IIF((ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY t.name DESC)) > 1,' UNION ALL ','')
FROM
sys.tables t
)
SELECT #SQLStatement = STUFF(
(SELECT ' ' + TableSelect
FROM
cteSelectStatements
ORDER BY
TableName
FOR XML PATH(''))
,1,1,'')
PRINT #SQLStatement
--EXECUTE #SQLStatement
Found this query here on Stack Overflow which I found very helpful to pull all table names and corresponding columns from a Microsoft SQL Server Enterprise Edition (64-bit) 10.50.4286 SP2 database.
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
It produces a table with two columns like this, each row has the table name in column 01 and the corressponding columns in column 02:
What I really want however is something like this, one column for each table name and the tables columns listed below it like this:
I've already started doing this manually in Excel, but with over 5000 rows returned it would be really nice if there was a way to format the results in the query itself to look like this. Thanks in advance!
As everyone is telling you, this is an un-SQL-y thing to do. Your resultset will have an arbitrary number of columns (equal to the number of user tables in your database, which could be huge). Since the resultset must be rectangular, it will have as many rows as the maximum number of columns in any of your tables, so many of the values will be NULL.
That said, a straightforward dynamic PIVOT gets you what you want:
DECLARE #columns nvarchar(max);
DECLARE #sql nvarchar(max);
SET #columns = STUFF ( (
SELECT '],[' + t.name
FROM sys.tables t
WHERE t.type = 'U'
FOR XML PATH('') ), 1, 2, '')
+ ']';
SET #sql = '
SELECT ' + #columns + '
FROM
(
SELECT t.Name tName
, c.Name cName
, ROW_NUMBER() OVER (PARTITION BY t.Name ORDER BY c.Name) rn
FROM sys.columns c
JOIN sys.tables t ON t.object_id = c.object_id
WHERE t.type = ''U''
) raw
PIVOT (MAX(cName) FOR tName IN ( ' + #columns + ' ))
AS pvt;
';
EXECUTE(#sql);
This is what it produces on my master database:
spt_fallback_db spt_fallback_dev spt_fallback_usg spt_monitor MSreplication_options
------------------- ------------------- ------------------- --------------- ----------------------
dbid high dbid connections install_failures
name low lstart cpu_busy major_version
status name segmap idle minor_version
version phyname sizepg io_busy optname
xdttm_ins status vstart lastrun revision
xdttm_last_ins_upd xdttm_ins xdttm_ins pack_errors value
xfallback_dbid xdttm_last_ins_upd xdttm_last_ins_upd pack_received NULL
xserver_name xfallback_drive xfallback_vstart pack_sent NULL
NULL xfallback_low xserver_name total_errors NULL
NULL xserver_name NULL total_read NULL
NULL NULL NULL total_write NULL
(11 row(s) affected)
It might be easiest to do for example something like this:
Build a comma separated list using for XML path, for example like this.
Then copy that result to excel and use data to columns to create separate columns from the items
Use copy + paste special -> transpose to turn rows into columns
I have a very fat table with more than 100 columns. I want to count the number of value of one column. But in order to do that I have to group by all the other columns (which is a pain). Is there a way to group the table by all the columns except for that one?
It works like:
select * [except col],count(col)
from table
group by * [except col];
The table is like:
(Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8,Col9.....,Col100)
(1,1,2,2,3,4,5,6......,X)
(1,1,2,2,3,4,5,6......,Y)
(1,0,2,2,3,4,5,6......,X)
(1,0,2,2,3,4,5,6......,X)
(1,0,2,2,3,4,5,6......,Y)
(1,0,2,2,3,4,5,6......,Z)
result should be
(1,1,2,2,3,4,5,6......,2)
(1,0,2,2,3,4,5,6......,4)
Agree with Gordon, if you still want to try the traditional way and don't want to mention 100 columns.
Try this:
declare #Colsql Nvarchar(Max)
Select #ColSql = isnull(#ColSql + ',','') + '['+c.name+']'
from sys.tables t inner join sys.columns c
on t.object_id = c.object_id
inner join sys.schemas sc
on t.schema_id = sc.schema_id
Where t.name = #TableName and sc.name = #SchemaName
and c.name <> #ColumnToExclude
Exec('Select ' +#ColSql+ 'Count(#ColumnToExclude) From #TableName Group By '+#ColSql)
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]