query by partial column name - sql

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;

Related

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

How to display the table name in a union query

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.

How to get count across multiple tables

I am using this code to get ABC count from all tables having 72 table
if I use
declare #SQL nvarchar(max)
declare #Countt bigint
SELECT #SQL = STUFF(( SELECT ' ; SELECT COUNT(ABC) FROM ' + INFORMATION_SCHEMA.TABLES.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES LEFT OUTER JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME where INFORMATION_SCHEMA.TABLES.TABLE_TYPE =N'BASE TABLE' AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME =N'ABC'
FOR XML PATH('')),1,2,'')
SET #SQL = #SQL
PRINT #SQL
EXECUTE (#SQL)
but I am getting 72 results one by one but I just want to get sum of all 72 results,for example if ABC have 10 rows in 4 Tables so it should be return 40 please suggest where I am wrong or any other better way
Everyone is right just need to add schema if there is different ones:
declare #SQL nvarchar(max)
declare #Countt bigint
SELECT #SQL = STUFF((
SELECT DISTINCT ' UNION ALL SELECT COUNT(ABC) AS CountAmount FROM ' + INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA + '.' + INFORMATION_SCHEMA.TABLES.TABLE_NAME AS [text()]
FROM INFORMATION_SCHEMA.TABLES
LEFT OUTER JOIN INFORMATION_SCHEMA.COLUMNS
ON INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
WHERE INFORMATION_SCHEMA.TABLES.TABLE_TYPE =N'BASE TABLE'
AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME =N'ABC'
FOR XML PATH('')),1,11,'')
SET #SQL = 'SELECT SUM( CountAmount ) AS TotalSum FROM (' + #SQL + ' ) AS T '
PRINT #SQL
EXECUTE (#SQL)
declare #SQL nvarchar(max)
declare #Countt bigint
SELECT #SQL = STUFF(( SELECT ' UNION ALL SELECT COUNT(ABC) AS noCount FROM ' + INFORMATION_SCHEMA.TABLES.TABLE_NAME FROM INFORMATION_SCHEMA.TABLES LEFT OUTER JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME where INFORMATION_SCHEMA.TABLES.TABLE_TYPE =N'BASE TABLE' AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME =N'ABC' FOR XML PATH('')),1,10,'')
SET #SQL = 'SELECT COUNT(*) FROM (' + #SQL + ')A'
PRINT #SQL
EXECUTE (#SQL)
You need to use an aggregate function and group your results. So if Ive read your sql correctly, group by INFORMATION_SCHEMA.TABLES.TABLE_NAME
Use a cursor and iterate over each table one by one. When you generate your dynamic sql string, select the results into a variable like so:
select #TableCount = Count(ABC) From SomeTable
set #TotalCount = #Totalcount + #TableCount

Global Update (All Rows) On One SQL Table With The Same Criteria

IS there a way to run this across every column in a table:
UPDATE dbo.stage_a
SET Statement_Name= NULL
WHERE Statement_Name='""';
I am trying to tidy up after a data import.
Dynamic query plus Information_schema.columns. Try this.
DECLARE #cols NVARCHAR(max)='UPDATE dbo.stage_a set '
SELECT #cols += COLUMN_NAME + '=case when ' + COLUMN_NAME
+ ' = '""' then null else '+COLUMN_NAME+' end,'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'stage_a'
AND TABLE_SCHEMA = 'dbo'
SELECT #cols = LEFT(#cols, Len(#cols) - 1)
PRINT #cols
EXEC Sp_executesql #cols
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
Like this example you should specify all coloumns.(separated by commas)
If you want to replace all coloumns with NULL why don't you delete the rows:
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste'
You meed to first get the all columns list by using the INFORMATION_SCHEMA.COLUMNS
DECLARE #tableName varchar(10)
SET #tableName = 'mm'
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
SELECT #sql = #sql + 'UPDATE ' + #tableName + ' SET ' + c.name + ' = NULL WHERE ' + c.name + '= ''';'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE t.name = #tableName AND y.name IN ('varchar', 'nvarchar', 'char', 'nchar')
EXEC (#sql)
Query is not tested may need to tweak as per your need

Getting Multipart Identifier could not be bound using sp_MSforeachtable

I'm using the sp_MSForeachtable to retrieve the columnames of all tables and concatenating the columnames in a single string. I'm using the following query. I've executed the same providing the parameter through a variable for a single table and works perfectly, but when executed from the SP it fails with the error 'The multi-part identifier "dbo.TableNm" could not be bound.'
DECLARE #query nvarchar(max)
SELECT #query =
'DECLARE #Names VARCHAR(255)
DECLARE #DB VARCHAR(255)
SELECT #Names = COALESCE(#Names + '', '', '''') + COLUMN_NAME FROM Information_Schema.COLUMNS
WHERE TABLE_NAME = ?
SELECT TOP 1 #DB = TABLE_CATALOG FROM Information_Schema.COLUMNS
WHERE TABLE_NAME = ?
SELECT #DB AS [DataBase], ? AS [Table], #Names AS [Columns]'
EXEC sp_MSforeachtable #query
I thought the error might be associated with having multiple tables with the same name in different databases so I tried pre-fixing the database but i still get the same error.
DECLARE #query nvarchar(max)
SELECT #query =
'DECLARE #Names VARCHAR(255)
DECLARE #DB VARCHAR(255)
DECLARE #TableNm VARCHAR(255) = ?
SET #DB = ''People_Directory''
SELECT #Names = COALESCE(#Names + '', '', '''') + COLUMN_NAME FROM Information_Schema.COLUMNS
WHERE TABLE_NAME = #TableNm
AND TABLE_CATALOG = #DB
SELECT #DB AS [DataBase], #TableNm AS [Table], #Names AS [Columns]'
EXEC sp_MSforeachtable #query
I'll keep trying bu I'm running out of ideas. Any thoughts?
The ? in the query will be replaced with the quoted schema-qualified name of the table. It will not be enclosed in quotes, so your query is equivalent to:
SELECT ...
WHERE TABLE_NAME = [dbo].[YourTable]
...
SELECT #DB As [DataBase], [dbo].[YourTable] As [Table], #Names As [Columns]
This will obviously generate an error.
You'll need to add the quotes around the ? so that it's treated as a string. However, your query still won't work, as the TABLE_NAME column doesn't include the schema name, and isn't quoted.
To make the query work as expected, you'll need to combine the TABLE_SCHEMA and TABLE_NAME columns, and make sure the values are quoted, before comparing to the current table name:
DECLARE #query nvarchar(max)
SELECT #query =
'DECLARE #Names VARCHAR(255)
DECLARE #DB VARCHAR(255)
SELECT #Names = COALESCE(#Names + '', '', '''') + COLUMN_NAME FROM Information_Schema.COLUMNS
WHERE QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) = ''?''
SELECT TOP 1 #DB = TABLE_CATALOG FROM Information_Schema.COLUMNS
WHERE QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) = ''?''
SELECT #DB AS [DataBase], ''?'' AS [Table], #Names AS [Columns]'
EXEC sp_MSforeachtable #query
EDIT:
You don't actually need to use sp_MSforeachtable to do this. Using one of the methods from this article, you can retrieve this information in a single query:
SELECT
T.TABLE_CATALOG As [DataBase],
QUOTENAME(T.TABLE_SCHEMA) + '.' + QUOTENAME(T.TABLE_NAME) As [Table],
STUFF(
(
SELECT ', ' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS As C
WHERE C.TABLE_CATALOG = T.TABLE_CATALOG
And C.TABLE_SCHEMA = T.TABLE_SCHEMA
And C.TABLE_NAME = T.TABLE_NAME
ORDER BY C.ORDINAL_POSITION
FOR XML PATH(''), TYPE
).value('.', 'varchar(max)')
, 1, 1, '') As [Columns]
FROM
INFORMATION_SCHEMA.TABLES As T
;