Append Table Name to Field Name with Select * - sql

Sorry if this is a duplicate. I have searched but only find aliasing fields and tables.
I have a query:
SELECT *
FROM MyTable1 ca LEFT OUTER JOIN MyTable2 dcn ON dcn.dstrct_code = ca.dstrct_code
LEFT OUTER JOIN MyTable2 cdn ON cdn.dstrct_code = ca.cost_dstrct_cde
LEFT OUTER JOIN MyTable3 bb ON bb.supplier_code = ca.supplier_code
WHERE ca.dstrct_code = '0001'
AND ca.req_232_type = 'P'
AND ca.requisition_no = '264982 000'
AND ca.alloc_count = '01'
ORDER BY ca.alloc_count ASC
Please dont shoot me down for using * im not done with the query yet. If I execute this query I get a row of data however the tables I am selecting from all have a good number of fields and many are simularly named. So my question is... Is there anyway to select * from and append the table name to the field name so it is more obvious which field belongs to which table?

I don't think there's a way to do that directly but you can do this instead. Run a query like this:
SELECT
(case t.name when 'MyTable1' then 'ca' when 'MyTable2' then 'dcn' when 'MyTable3' then 'cdn' when 'MyTable4' then 'bb' end)
+ '.' + c.name
+ ' AS "' + t.name + '.' + c.name + '",'
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE t.name in ('MyTable1', 'MyTable2', 'MyTable3', 'MyTable4')
ORDER BY t.name
Run it, preferably with results to Text (Ctrl+T), and use the results instead of the * in your original query. You have to manually remove the comma from the last line.
If you like the approach, you could streamline the process with some dynamic SQL.

Related

Set table name in a SELECT statement from a nested select

I have a table in MSSQL which has been called tables_list, it has a list of tables.
How can I use this list in another SELECT to count number of rows in each table and reach a list like the following picture:
SELECT T.[TABLE_NAME], count(*) AS NUMBERS
FROM [db_name].[schema_name].[T.[TABLE_NAME]]
(SELECT [TABLE_NAME],
FROM [db_name].[schema_name].[tables_list]) T
in sql server you can use system partition table to get the row counts in a database :
SELECT * FROM
(SELECT
QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName],
SUM(sPTN.Rows) AS [RowCount]
FROM
sys.objects AS sOBJ
INNER JOIN sys.partitions AS sPTN ON sOBJ.object_id = sPTN.object_id
WHERE
sOBJ.type = 'U'
AND sOBJ.is_ms_shipped = 0x0
AND index_id < 2 -- 0:Heap, 1:Clustered
GROUP BY
sOBJ.schema_id,
sOBJ.name
ORDER BY [TableName]) X
WHERE X.[TableName] IN
(SELECT
CONCAT('[schema_name].[prefix', [TABLE_NAME], ']')
FROM [db_name].[schema_name].[tables_list])

Query to select all tables with specific last column Ibm Db2 z/os

Goal: I need to create a query to select all tables with specific last column Ibm Db2 z/os
So I know I need to change my where clause for this but pretty much I want to select all the tables in my schema that have the last column as BATCH_ID. I've tried a length based where clause but can't figure it out also I know MySQL has an ordinal position feature but that's not in IBM DB2 z/Os as far as I've seen. Any help would be appreciated.
select c.tabschema as schema_name,
c.tabname as table_name
from syscat.columns c
inner join syscat.tables t on
t.tabschema = c.tabschema and t.tabname = c.tabname
where c.colname = 'BATCH_ID' AND c.tabschema = 'WRIT5P1'
AND c.tabname not like 'OLD%'
and t.type = 'T'
order by schema_name, table_name;
SYSIBM.SYSTABLES
SYSIBM.SYSCOLUMNS
SELECT T.NAME AS TABLE_NAME
FROM SYSIBM.SYSTABLES T
JOIN SYSIBM.SYSCOLUMNS C ON C.TBNAME = T.NAME AND C.TBCREATOR = T.CREATOR
WHERE T.TYPE = 'T' AND T.CREATOR = 'WRIT5P1'
AND T.NAME NOT LIKE 'OLD%'
AND C.NAME = 'BATCH_ID'
AND C.COLNO = T.COLCOUNT
I don't remember if C.COLNO starts from 0 or 1. Edit the query accordingly, if it starts from 0.

List the tables used by the sql script, and the nature of access to the table

I have a script with thousand of lines and I want to extract all the tables (& temp tables) the script references, and also the nature of access to the table such as select, insert, update or delete. Is there a tool we can use for this purpose?
Sample script (input):
SELECT * FROM Table1
UPDATE Table1 SET Col1 = 1
DELETE FROM Table2
EXEC 'INSERT INTO #Table3 SELECT ''Test'''
Sample output:
1. Table1 - select, update
2. Table2 - delete
3. #Table3 - insert
You may find the following query useful, however, one thing it doesn't give you is the references from dynamic SQL statements (and perhaps also table variables and temp tables).
I think to get the level of information you're looking for you'd probably need to write your own script/program. Previously I wrote something that gave me the results from the below query, including any dynamic SQL references, in C# using SQL Server Management Objects (SMO).
SELECT DISTINCT
OBJECT_SCHEMA_NAME(D.referencing_id) referencing_object_schema
, OBJECT_NAME(D.referencing_id) referencing_object_name
, O.[type_desc] referencing_object_type
, D.referenced_schema_name
, D.referenced_entity_name
, D.referenced_id
,
CASE
WHEN O_REF.[object_id] IS NOT NULL THEN O_REF.[type_desc]
WHEN T.user_type_id IS NOT NULL THEN 'USER_DEFINED_TYPE'
END referenced_object_type
FROM
sys.sql_expression_dependencies D
LEFT JOIN sys.objects O ON D.referencing_id = O.[object_id]
LEFT JOIN sys.objects O_REF ON D.referenced_id = O_REF.[object_id]
LEFT JOIN sys.types T ON D.referenced_id = T.user_type_id
There is a system function called: fn_dblog. You could use it as below:
IF OBJECT_ID('tempdb..#tempLog') IS NOT NULL DROP TABLE #tempLog
-- Raw Data
SELECT DISTINCT
[AllocUnitName],
Operation
INTO #tempLog
FROM sys.fn_dblog(NULL,NULL)
WHERE Operation IN ('LOP_INSERT_ROWS','LOP_MODIFY_ROW',
'LOP_DELETE_ROWS','LOP_BEGIN_XACT','LOP_COMMIT_XACT')
AND [AllocUnitName] is not null
ORDER By [AllocUnitName], Operation
-- SELECT * FROM #tempLog
-- Display Enhancement and Grouping
SELECT [AllocUnitName], Operations = STUFF((
SELECT N', ' + REPLACE(operation,'LOP_', '')
FROM #tempLog
WHERE [AllocUnitName] = x.[AllocUnitName]
FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'')
FROM #tempLog AS x
WHERE [AllocUnitName] is not null
GROUP BY [AllocUnitName]
ORDER BY [AllocUnitName]

T-SQL Query to get table dependencies for all tables in database

I have the start of a query below which gives me dependencies of a particular table:
SELECT DISTINCT OBJECT_NAME(object_id) AS referencing_object_name
FROM sys.sql_dependencies
WHERE referenced_major_id = OBJECT_ID('TABLE_NAME_HERE')
But is there a way to alter this to show:
1) The above with a column with tablename being populated
2) The above relating to ALL tables within a set database (not just a single table as the original query shows)
3) All results on a single row
Final output looking like image below:
screenshotoffinalquery
.
.
.
EDIT:
I seem to be very close with this, but last column is duplicating a single result
SELECT DISTINCT b.name, a.referenced_major_id, b.object_id,
substring((
SELECT ' || ' +OBJECT_NAME(a.object_id)
FROM sys.sql_dependencies a JOIN sys.tables b ON a.referenced_major_id = b.object_id
For XML PATH ('')
), 2, 1000) AS [TextLine]
FROM sys.sql_dependencies a JOIN sys.tables b ON a.referenced_major_id = b.object_id
ORDER BY b.name ASC

Search string in SQL with action on table

I found on internet some stored procedure to search string in database, regularly it's used by table name.
My procedure contains a SELECT statement like this:
select distinct s.name
from sysobjects s
inner join syscomments c on c.id = s.id
and charindex(#keyword,c.text) > 0
where s.type IN ('V', 'P')
order by 1
My action want more than this, I want to search table name with action on that like insert, update or select. It means only find table name(keyword) has action insert or update or select and show me where it's used (procedure name, view...)
Is it possible to do?
First, dont use sysobjects and syscomments as they have been deprecated for quite some time now.
If you just care that the word appears in the object text, you can use a wildcard search like this
select top 100 *
from sys.sql_modules sm
inner join (select searchString = 'insert' union all
select searchString = 'update' union all
select searchString = 'delete') x
on sm.definition like '%' + x.searchString + '%'