How to display the table name in a union query - sql

The following script is working well:
DECLARE #SelectClause VARCHAR(100) = 'SELECT id_contato'
,#Query VARCHAR(8000) = ''
SELECT #Query = #Query + #SelectClause + ' FROM ' + TABLE_NAME + ' UNION ALL '
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_NAME LIKE '%zumbi' or TABLE_NAME like '%engajado%')
SELECT #Query = LEFT(#Query, LEN(#Query) - LEN(' UNION ALL '))
EXEC (#Query)
But I need a second column with the table name to identify where the information came from.
How can I do that?

You're utilizing the table_name field already in your query, just need to add it to your SELECT and quote it properly so it comes back as string literal:
DECLARE #SelectClause VARCHAR(100) = 'SELECT id_contato'
,#Query VARCHAR(8000) = ''
SELECT #Query = #Query + #SelectClause + ','''+Table_Name+''' AS Table_Name FROM ' + TABLE_NAME + ' UNION ALL '
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_NAME LIKE '%zumbi' or TABLE_NAME like '%engajado%')
SELECT #Query = LEFT(#Query, LEN(#Query) - LEN(' UNION ALL '))
EXEC (#Query)
Updated quotes, works for me in SQL Server.

Related

How to pass table name and column name dynamic in SQL

I was trying to pass table name and column name dynamic, this is as part of SSIS process I am trying this stored procedure below.
CREATE PROCEDURE [lnd].[Get_ANCNotullColumn]
(#PassedTableName AS NVarchar(255),
#PassedColumnName AS NVARCHAR(100))
AS
BEGIN
DECLARE #ActualTableName AS NVarchar(255)
SELECT #ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #PassedTableName
DECLARE #sql AS NVARCHAR(MAX)
SELECT #sql = 'SELECT COUNT(*) FROM ' + #ActualTableName + ';'
DECLARE #final AS NVARCHAR(MAX)
SELECT #final = #sql + 'WHERE ' + #PassedColumnName + ' IS NULL OR ' + #PassedColumnName + '='''
EXEC(#SQL)
END
On executing this, I am NOT getting count as result, instead I am getting execution success.
EXEC [lnd].[Get_ANCNotullColumn] 'lnd.ANC_LND_ItemOverride', 'comments'
I need to get the count as output.
Also my simple direct query is like this
SELECT COUNT(*)
FROM lnd.ANC_LND_ItemOverride
WHERE Comments IS NULL OR Comments = '' -- 3 is the output
I think you may need to modify you value passing and your concatenation values.
from this statement you need to remove the semi colon as it will throw error
SELECT #sql = 'SELECT COUNT(*) FROM ' + #ActualTableName + ';'
While passing blank values you need additional quotes
SELECT #final = #sql + 'WHERE ' + #PassedColumnName + ' IS NULL OR ' + #PassedColumnName + '= '''''
While execution I believe you wanted to execute final instead of SQL
I think below should give your output:
CREATE PROC [lnd].[Get_ANCNotullColumn]( #PassedTableName as NVarchar(255),#PassedColumnName AS
NVARCHAR(100))
AS
BEGIN
DECLARE #ActualTableName AS NVarchar(255)
SELECT #ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #PassedTableName
DECLARE #sql AS NVARCHAR(MAX)
SELECT #sql = 'SELECT COUNT(*) FROM ' + #ActualTableName + ' '
DECLARE #final AS NVARCHAR(MAX)
SELECT #final = #sql + 'WHERE ' + #PassedColumnName + ' IS NULL OR ' + #PassedColumnName + '='''''
EXEC(#final)
END

query by partial column name

I have a
Checklist table and
there is 27 columns named "check1", "check2"..."check27".I would like to get all this values doing a query something like:
SELECT "check*" FROM Checklist;
Is this possible?
Which database? postgres, sqlite, mysql?
If select * is not an option, the most flexible approach is creating a dynamic query. You will first need to get the column names and then build your query:
DECLARE #tableName as varchar(100);
SET #tableName = 'Checklist';
DECLARE #columnList varchar(300);
SELECT #columnList = COALESCE(#columnList + ', ', '') + sc.name
FROM sysobjects so
INNER JOIN syscolumns sc ON so.id = sc.id
WHERE so.name = #tableName
AND sc.name LIKE 'check%'
DECLARE #query as varchar(4000);
SET #query = 'SELECT ' + #columnList + ' FROM ' + #tableName;
EXEC(#query);
The ending #query should contain SELECT check1, check2, check... FROM Checklist.
In Sql Server, this is terrible but you could do it... Building dynamic SQL
check% being your check* in the Select #columns query
DECLARE #columns NVARCHAR(max);
SELECT #columns = STUFF((
SELECT ',' + column_name
FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'Checklist'
AND column_name LIKE 'check%'
FOR XML path('')
), 1, 1, '')
DECLARE #statement nvarchar(max) = 'SELECT ' + #columns + ' FROM Checklist'
EXECUTE sp_executesql #statement
Troll ass answer...
SELECT check1,check2,check3,check4,check5,check6,check7,check8,check9,check10,check11,check12,check13,check14,check15,check16,check17,check18,check19,check20,check21,check22,check23,check24,check25,check26,check27 FROM Checklist;

T-SQL: Select data from all tables reverted by INFORMATION_SCHEMA.TABLES

I need to extract data from all tables that were reverted by following query:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'ERP_%'
I've tried to execute following query, but without success:
SELECT *
FROM
(SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'ERP_%')
WHERE STATUS = 'XXX'
Looking forward to your assistance.
You may try to generate a dynamic SQL statement and execute it:
-- Declarations
DECLARE #stm nvarchar(max)
SET #stm = N''
-- Dynamic SQL
SELECT #stm = (
SELECT CONCAT(
N'SELECT * FROM ',
QUOTENAME(TABLE_NAME),
N' WHERE [STATUS] = ''XXX''; '
)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'ERP_%'
FOR XML PATH('')
)
-- Execution
PRINT #stm
EXEC sp_executesql #stm
Try this query using dynamic SQL:
declare #sql varchar(max) = '';
select #sql = #sql + 'select * from ' + TABLE_NAME + ' where [status] = ''XXX''; '
from INFORMATION_SCHEMA.TABLES
where TABLE_NAME like 'ERP_%';
exec(#sql);

select the max(date) and table name as columns

I have many tables like:
A_names ( updated_at date )
B_names (updated_at date )
C_names (updated_at date )
I want max of updated_date and table name for all the table like '%names%' in the database
select * into #temp1
from INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME like '%names%'
How to do it ..? thanks in advance
Try this :-
Select name ,modify_date from sys.tables
where name like '%names'
And avoid using INFORMATION_SCHEMA.TABLES instead use catalog views .
Check this article out The case against INFORMATION_SCHEMA views
Dynamically create a SQL statement and then run that command.
DECLARE #dml nvarchar(max) = N''
SELECT #dml += ' UNION ALL SELECT ''' + name + ''' AS tableName, MAX(updated_at) AS maxUpdated_at FROM '
+ QUOTENAME(name)
FROM sys.tables
WHERE name like '%names%'
PRINT #dml
SET #dml = STUFF(#dml, 1, 10, '')
EXEC sp_executesql #dml
Option without a STUFF function
DECLARE #dml nvarchar(max)
SELECT #dml = ISNULL(#dml + ' UNION ALL', '') + ' SELECT ''' + name + ''' AS tableName, MAX(updated_at) AS maxUpdated_at FROM '
+ QUOTENAME(name)
FROM sys.tables
WHERE name like '%names%'
EXEC sp_executesql #dml
SELECT MAX(updated_at_date)
FROM table1
I'm a bit confused from the description about your table names. Anyways this is the way you select the max date.
Probabaly Praveen's answer is a solution to your problem, but in pseudocode
DECLARE #SqlStmt NVARCHAR(2000)
For Each TableName in 'Select name from sys.tables'
{
if #SqlStmnt <> '' #SqlStmnt = #SqlStmnt + ' UNION '
#sqlStmnt = #sqlStmnt + ' SELECT Max(updated_at_date) AS MAXDATE FROM ' + TableName
}
**EXECUTE ('SELECT MAX(MAXDATE) FROM (' + #SqlStmt + ')')**

String functions to generate dynamic query in SQL Server 2008

Select * from MyTable gives the following result
AttributeID AttributeName
------------------------------------ ------------------------
6B93119B-263B-4FED-AA89-198D26A3A3C4 DOB
E27DBA94-F387-460A-BC02-84878692BDF6 Sex
ABF3B85C-0DEA-44FE-857A-AC63520F7294 History
Now I want to generate a dynamic query in the following format (to be used with PIVOT)
SELECT
[6B93119B-263B-4FED-AA89-198D26A3A3C4] DOB,
[E27DBA94-F387-460A-BC02-84878692BDF6] Sex,
[ABF3B85C-0DEA-44FE-857A-AC63520F7294] History
How can I do it in SQL Server 2008?
DECLARE #query VARCHAR(MAX)
SET #query = 'SELECT '
SELECT #query = #query + '[' + CONVERT(NVARCHAR(50),AttributeID) + '] ' + AttributeName + ','
FROM MyTable
PRINT #query
The following produces the desired result for me:
DECLARE #Query VARCHAR(MAX);
SET #Query = 'SELECT ';
WITH Data AS (
SELECT '6B93119B-263B-4FED-AA89-198D26A3A3C4' AS AttributeID, 'DOB' AS AttributeName
UNION ALL
SELECT 'E27DBA94-F387-460A-BC02-84878692BDF6', 'Sex'
UNION ALL
SELECT 'ABF3B85C-0DEA-44FE-857A-AC63520F7294', 'History'
)
SELECT #Query = #Query + '''' + AttributeID + ''' ' + AttributeName + ', '
FROM Data
SET #Query = SUBSTRING(#Query, 1, LEN(#Query) - 1);
SELECT #Query
Edit: Just to be clear, the section of SQL in the above sample beginning "WITH Data AS (" and ending at the close bracket (")") is just there as sample data. You can omit it entirely, so the sample becomes:
DECLARE #Query VARCHAR(MAX);
SET #Query = 'SELECT ';
SELECT #Query = #Query + '''' + AttributeID + ''' ' + AttributeName + ', '
FROM MyTable
SET #Query = SUBSTRING(#Query, 1, LEN(#Query) - 1);
SELECT #Query