SQL get name of table or view currently being queried - sql-server

I have a long list of tables / views, and I just need a count of the records and the name of the object being queried, for example...
SELECT COUNT(*), TableOrViewName FROM TableOrView
UNION ALL
SELECT COUNT(*), TableOrViewName FROM TableOrView
UNION ALL
SELECT COUNT(*), TableOrViewName FROM TableOrView

Related

SQL Server Union All with one different column

I am using union all function inside two tables. Two tables are exactly the same except one column.
Here is my code:
SELECT x.InventoryTransTempID
,x.InventoryTransID
FROM (
SELECT *
FROM InventoryTransTemp
UNION ALL
SELECT *
FROM InventoryTrans
) x
The only column which is different is the Identity column. In first table is called InventoryTransTempID and in Second InventoryTransID. Is there any way to inform sql server that if column name is InventoryTrans just renamed it to InventoryTransTempID.
My exception is:
Invalid column name 'InventoryTransID'.
This error happens because when you perform union operation between two columns and try to get output in one column the name of column is the name of upper one column name as shown below.
Select 'a' as column1
union all
Select 'b' as column2
The output will be here
column1
-------
a
b
Here as per the above statement column2 is mixed with column1, So you can not get both the column name in outer query.
To check the column name you should first check the output of the inner query which is as below.
select * from InventoryTransTemp union all select * from InventoryTrans
The result of UNION ALL is all rows from both tables and the names of the columns are taken from the 1st query of the unioned queries.
So you can't have in the results both column names.
In this query:
select * from InventoryTransTemp
union all
select * from InventoryTrans
the column's name will be InventoryTransTempID,
and in this query:
select * from InventoryTrans
union all
select * from InventoryTransTemp
the column's name will be InventoryTrans.
You can change the name if you alias it in the 1st query.

Collate data from different Databases into same output window

I need to display data in different columns in the same output window from multiple different database sources. It would be ok to output this data to a file if necessary. For example say I have the following script that I need run on databases with identical schema:
SELECT TOP 3 item_id, COUNT(*) as itemcount_db1
FROM DB1.dbo.table
GROUP BY item_id ORDER BY itemcount_db1
SELECT TOP 3 item_id, COUNT(*) as itemcount_bd2
FROM DB2.dbo.table
GROUP BY item_id ORDER BY itemcount_bd2
So that the output would not be in two sequential and separate windows (as I hundreds of DBs and want to do a single copy and paste). I'm happy to create all of the individual scripts to get the data, just need to combine them somehow.
For one, you can use sp_MSforeachdb or a potential better one by Aaron Bertrand so you don't have to copy and paste all the scripts. I'm not sure you'd want the results going horizontally here, but instead just create a column with the DB flag. Here is a way using UNION and a CTE (since you need the order by for TOP).
with db1 as(
SELECT TOP 3
item_id,
COUNT(*) as itemcount
,'DB1'
FROM
DB1.dbo.table
GROUP BY
item_id
ORDER BY
itemcount_bd2)
db2 as(
SELECT TOP 3
item_id,
COUNT(*) as itemcount
,'DB2'
FROM
DB2.dbo.table
GROUP BY
item_id
ORDER BY
itemcount_bd2)
select * from db1
union all
select * from db2

Mixing UNION ALL and DISTINCT in SQL

I have a SQL Server 2014 database. I am building a stored procedure that will return counts across several tables that match certain criteria. At this time, I have the following:
SELECT 'Table1' TableName, COUNT(0) TotalRows FROM dbo.[SomeTable]
UNION ALL
SELECT COUNT(DISTINCT [Name]) AS 'Department' FROM [Department]
UNION ALL
SELECT COUNT(DISTINCT [SubDepartment]) AS 'SubDepartment' FROM [Department]
UNION ALL
SELECT 'Table2' TableName, COUNT(0) TotalRows FROM dbo.[AnotherTable]
When I execute this SQL, I get an error that says:
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
If I remove the two lines that begin with SELECT COUNT(... it works just fine. However, I need to get the number of department names and the number of sub-department names. How can I do this while still getting the counts from the other tables?
Thanks!

Perform Query and count rows on multiple identical table

I have multiple tables created for each date to store some information for each date.
For example History3108,History0109..etc All of these tables share same schema. Some time i need to query multiple tables and get the rows and count of records. What is the faster way of doing this in oracle and SQL Server?
Currently i am doing like this...
When i need count of multiple tables: Select count(*) for each table and add
When i need records of multiple tables: select * from table1, select * from table2 (Basically select * for each table.)
Would this give better performance if we include all of the queries in one transaction?
With UNION you can get records from multiple tables that shares the same datatype group and column names. For example, if you want to see all records from multiple tables:
(select * from history3108)
union all
(select * from history0109)
union all
(select * from history0209)
/* [...] and so on */
and if you want to count all records from these tables:
select count(*) from (
(select * from history3108)
union all
(select * from history0109)
union all
(select * from history0209)
/* [...] and so on */
);
Oracle Docs - The UNION [ALL], INTERSECT, MINUS Operators

How to use UNION while inserting in a table using SELECT clause from many tables in SQL Server 2000

I am using SQL Server 2000. I have multiple criterias which i have to use to extract different sets of records from mumtiple table in another table. I am using
INSERT INTO T1(A,B)
(SELECT E,R FROM T2)
UNION
(SELECT Z,X FROM T3)
Query analyzer is throwing error that while using UNION, you should use ORDER BY clause with SELECT. Even after doing that i m not able to union two different queries which are returing same columns in their select clause.
What is the right way to insert using SELECTS with UNIONS and ORDER BY.
The pseudo is too cryptic (reduced?)
It is very unlikely to get 2 columns per cross join of 2 tables in each of the union components
INSERT INTO T1(A,B)
(SELECT * FROM E,R)
UNION
(SELECT * FROM Z,X)
Note: If you have ANY order by clause at all, it must be at the end of the union
INSERT T1(A,B)
SELECT P,Q FROM E,R
UNION
SELECT R,S FROM Z,X
#updated based on error text "Server: Msg 104, Level 15, State 1, Line 1 ORDER BY items must appear in the select list if the statement contains a UNION operator"
This occurs when you have a union that attempts to perform ORDER BY on a column that does not appear in the result. Consider a normal ORDER BY involving non-selected columns
select top 10 name from syscolumns order by xtype
The rows are consistent and the query can be satisfied. However, if you did
select top 10 name from syscolumns where xtype > 50
union all
select top 10 name from syscolumns where xtype < 50
order by xtype
EVEN IF xtype exists in both parts of the UNION, but the time it gets presented to ORDER BY (which works at the END over the entire result set), the column is not there. You would have to rewrite it (if you didn't want to show xtype) as
select name from (
select top 10 name, xtype from syscolumns where xtype > 50
union all
select top 10 name, xtype from syscolumns where xtype < 50
) x
order by xtype
Hope that helps

Resources