Suppose I have a view in which some of the column names are aliases, like "surName" in this example:
CREATE VIEW myView AS
SELECT
firstName,
middleName,
you.lastName surName
FROM
myTable me
LEFT OUTER JOIN yourTable you
ON me.code = you.code
GO
I'm able to retrieve some information about the view using the INFORMATION_SCHEMA views.
For example, the query
SELECT column_name AS ALIAS, data_type AS TYPE
FROM information_schema.columns
WHERE table_name = 'myView'
yields:
----------------
|ALIAS |TYPE |
----------------
|firstName |nchar|
|middleName|nchar|
|surName |nchar|
----------------
However, I would like to know the actual column name as well. Ideally:
---------------------------
|ALIAS |TYPE |REALNAME |
---------------------------
|firstName |nchar|firstName |
|middleName|nchar|middleName|
|surName |nchar|lastName |
---------------------------
How can I determine what the real column name is based on the alias? There must be some way to use the sys tables and/or INFORMATION_SCHEMA views to retrieve this information.
EDIT:
I can get close with this abomination, which is similar to Arion's answer:
SELECT
c.name AS ALIAS,
ISNULL(type_name(c.system_type_id), t.name) AS DATA_TYPE,
tablecols.name AS REALNAME
FROM
sys.views v
JOIN sys.columns c ON c.object_id = v.object_id
LEFT JOIN sys.types t ON c.user_type_id = t.user_type_id
JOIN sys.sql_dependencies d ON d.object_id = v.object_id
AND c.column_id = d.referenced_minor_id
JOIN sys.columns tablecols ON d.referenced_major_id = tablecols.object_id
AND tablecols.column_id = d.referenced_minor_id
AND tablecols.column_id = c.column_id
WHERE v.name ='myView'
This yields:
---------------------------
|ALIAS |TYPE |REALNAME |
---------------------------
|firstName |nchar|firstName |
|middleName|nchar|middleName|
|surName |nchar|code |
|surName |nchar|lastName |
---------------------------
but the third record is wrong -- this happens with any view created using a "JOIN" clause, because there are two columns with the same "column_id", but in different tables.
Given this view:
CREATE VIEW viewTest
AS
SELECT
books.id,
books.author,
Books.title AS Name
FROM
Books
What I can see you can get the columns used and the tables used by doing this:
SELECT *
FROM INFORMATION_SCHEMA.VIEW_COLUMN_USAGE AS UsedColumns
WHERE UsedColumns.VIEW_NAME='viewTest'
SELECT *
FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE AS UsedTables
WHERE UsedTables.VIEW_NAME='viewTest'
This is for sql server 2005+. See reference here
Edit
Give the same view. Try this query:
SELECT
c.name AS columnName,
columnTypes.name as dataType,
aliases.name as alias
FROM
sys.views v
JOIN sys.sql_dependencies d
ON d.object_id = v.object_id
JOIN .sys.objects t
ON t.object_id = d.referenced_major_id
JOIN sys.columns c
ON c.object_id = d.referenced_major_id
JOIN sys.types AS columnTypes
ON c.user_type_id=columnTypes.user_type_id
AND c.column_id = d.referenced_minor_id
JOIN sys.columns AS aliases
on c.column_id=aliases.column_id
AND aliases.object_id = object_id('viewTest')
WHERE
v.name = 'viewTest';
It returns this for me:
columnName dataType alias
id int id
author varchar author
title varchar Name
This is also tested in sql 2005+
Having spent a number of hours trying to find an answer to this, and repeatedly running into solutions that didn't work and posters that appeared to eventually give up, I eventually stumbled across an answer here that appears to work:
https://social.msdn.microsoft.com/Forums/windowsserver/en-US/afa2ed2b-62de-4a5e-ae70-942e75f887a1/find-out-original-columns-name-when-used-in-a-view-with-alias?forum=transactsql
The following SQL returns, I believe, exactly what you're looking for, it's certainly doing what I need and appears to perform well too.
SELECT name
, source_database
, source_schema
, source_table
, source_column
, system_type_name
, is_identity_column
FROM sys.dm_exec_describe_first_result_set (N'SELECT * from ViewName', null, 1)
Documentation on the sys.dm_exec_describe_first_result_set function can be found here, it's available in SQL Server 2012 and later:
https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-describe-first-result-set-transact-sql
Full credit to the poster on the link, I didn't work this out myself, but I wanted to post this here in case it's useful to anyone else searching for this information as I found this thread much more easily than the one I linked to.
I think you can't.
Select query hides actual data source it was performed against. Because you can query anything, i.e. view, table, even linked remote server.
Not a Perfect solution; but, it is possible to parse the view_definition with a high degree of accuracy especially if the code is well organized with consistent aliasing by 'as'. Additionally, one can parse for a comma ',' after the alias.
Of note: the final field in the select clause will not have the comma and I was unable to exclude items being used as comments (for example interlaced in the view text with --)
I wrote the below for a table named 'My_Table' and view correspondingly called 'vMy_Table'
select alias, t.COLUMN_name
from
(
select VC.COLUMN_NAME,
case when
ROW_NUMBER () OVER (
partition by C.COLUMN_NAME order by
CHARINDEX(',',VIEW_DEFINITION,CHARINDEX(C.COLUMN_NAME,VIEW_DEFINITION))-
CHARINDEX(VC.COLUMN_NAME,VIEW_DEFINITION)
) = 1
then 1
else 0 end
as lenDiff
,C.COLUMN_NAME as alias
,CHARINDEX(',',VIEW_DEFINITION,CHARINDEX(C.COLUMN_NAME,VIEW_DEFINITION)) diff1
, CHARINDEX(VC.COLUMN_NAME,VIEW_DEFINITION) diff2
from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE VC
inner join INFORMATION_SCHEMA.VIEWS V on V.TABLE_NAME = 'v'+VC.TABLE_Name
inner join information_schema.COLUMNS C on C.TABLE_NAME = 'v'+VC.TABLE_Name
where VC.TABLE_NAME = 'My_Table'
and CHARINDEX(',',VIEW_DEFINITION,CHARINDEX(C.COLUMN_NAME,VIEW_DEFINITION))-
CHARINDEX(VC.COLUMN_NAME,VIEW_DEFINITION) >0
)
t
where lenDiff = 1
Hope this helps and I look forward to your feedback
Related
I am using SQL Server 2008 R2.
Recently I got a database that contains the live data of a web-application.
By reviewing it I found that there are many tables that have dependencies i.e. already implied but not declared.
For example :
TableA have columns [Id], [Name], [Address]. Here [Id] is primary key.
TableB have columns [Id], [TableAId], [Salary]. Here [Id] is primary key, and column [TableAId] contains only values of [TableA].[Id] (not any value except TableA's Id), but it is not declared as a foreign key.
By Reviewing code, I found that both of the table's record are inserted in same event. So [TableB].[TableAId] column will have only values that [TableA].[Id] contains.
Now, I want to find the other dependencies like them.
Is it possible using SQL server query, tool or any third party software?
In the general case, I don't think you can count on TableA.Id to imply a foreign key reference to TableA. It might be referring to a different table that also stores id numbers from table A. I know you've reviewed the code in this specific case, but you're looking for a solution that doesn't require reviewing the code.
Anyway . . .
You can join tables on expressions. This query (PostgreSQL syntax) joins part of the column name to table names. In PostgreSQL, the function call left(t1.column_name, -2) returns all but the last two characters of t1.column_name; left(t1.column_name, -3) returns all but the last three. That's intended to match names like "TableAid" and "TableA_id".
select t1.table_catalog, t1.table_schema, t1.table_name,
t1.column_name, left(t1.column_name, -2),
t2.table_catalog, t2.table_schema, t2.table_name
from information_schema.columns t1
inner join information_schema.tables t2
on left(t1.column_name, -2) = t2.table_name or
left(t1.column_name, -3) = t2.table_name
where t1.column_name like '%id';
I believe this query will return the same rows. It's using SQL Server syntax, but I haven't tested it in SQL Server.
select t1.table_catalog, t1.table_schema, t1.table_name,
t1.column_name, left(t1.column_name, length(t1.column_name) - 2),
t2.table_catalog, t2.table_schema, t2.table_name
from information_schema.columns t1
inner join information_schema.tables t2
on left(t1.column_name, length(t1.column_name) - 2) = t2.table_name or
left(t1.column_name, length(t1.column_name) - 3) = t2.table_name
where t1.column_name like '%id';
Both these might return rows incorrectly, mainly because joins probably need to take into account the "table_catalog" column at the very least. I debated whether to include it. I finally decided to leave it out. I think that, if I were in your shoes, I'd want this query to have the maximum chance of returning some surprising rows.
Try some dependency checks.
--- Get the source objects, columns and dependent objects using the data.
select so.name as sourceObj
, so.type as sourceType
, c.name as colname
, st.name as coltype
, u.name as DependentObj
, d.selall as is_select_all
, d.resultobj as is_updated
, d.readobj as is_read
--, d.*
from sys.columns c
----- object that owns the column
inner join sys.objects so on so.object_id = c.object_id
inner join sys.types st on c.system_type_id = st.system_type_id
----- holds dependencies
inner join sysdepends d on d.id = c.object_id
----- object that uses the column
inner join sys.objects u on u.object_id = d.depid
You can list all the tables/views/procs, etc. The bits that are really good for your use case are:
, d.sellall as is_select_all
, d.resultobj as is_updated
, d.readobj as is_read
If any of these fields have 1, they are either selected, updated or retrieved directly.
I hope this may help a bit.
Enjoy
I have a table (DB_TableInfo) in my DB like the following
TableId Type
859374678 R
579845658 B
478625849 R
741587469 E
.
.
.
this table represents all tables in my DB. What I wanna do is to write a query to select tables of Type 'R', get their Id and return the Name of the table belonging to that Id (the TableName column is not available in the specified table)
Can anybody help me out?
I wanna write a query similar to this one!
SELECT TableID = OBJECT_NAME FROM [DB_TableInfo] WHERE Type = 'R'
From the mention of sys.objects and use of square brackets I assume you are on SQL Server.
You can use the object_name function.
SELECT OBJECT_NAME(TableID) /*Might match objects that aren't tables as well though*/
FROM [DB_TableInfo]
WHERE Type = 'R'
Or join onto sys.tables
SELECT T.name
FROM [DB_TableInfo] D
join sys.tables T ON D.TableID = T.object_id
WHERE D.Type = 'R'
And to exclude empty tables
SELECT t.name
FROM DB_TableInfo d
JOIN sys.tables t ON d.TableId = t.object_id
JOIN sys.dm_db_partition_stats ps ON ps.object_id = t.object_id
WHERE d.Type = 'R' and ps.index_id <= 1
GROUP BY d.TableId, t.name
HAVING SUM(ps.row_count) > 0
Would any of you know how to get the list of computed columns in a SQL Server database table?
I found sys.sp_help tablename does return this information, but only in the second result-set.
I am trying to find out if there is a better way of doing this. Something which only returns a single result set.
Check the sys.columns system catalog view:
SELECT *
FROM sys.columns
WHERE is_computed = 1
This gives you all computed columns in this database.
If you want those for just a single table, use this query:
SELECT *
FROM sys.columns
WHERE is_computed = 1
AND object_id = OBJECT_ID('YourTableName')
This works on SQL Server 2005 and up.
UPDATE: There's even a sys.computed_columns system catalog view which also contains the definition (expression) of the computed column - just in case that might be needed some time.
SELECT *
FROM sys.computed_columns
WHERE object_id = OBJECT_ID('YourTableName')
If you want to use the INFORMATION_SCHEMA views, then try
SELECT
COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA+'.'+TABLE_NAME),COLUMN_NAME,'IsComputed')
AS IS_COMPUTED,
*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='<Insert Your Table Name Here>'
For SQL Server 2000 the syntax is:
SELECT * FROM sys.columns
WHERE is_computed = 1
And the slightly more useful:
SELECT
sysobjects.name AS TableName,
syscolumns.name AS ColumnName
FROM syscolumns
INNER JOIN sysobjects
ON syscolumns.id = sysobjects.id
AND sysobjects.xtype = 'U' --User Tables
WHERE syscolumns.iscomputed = 1
sample output:
TableName ColumnName
===================== ==========
BrinksShipmentDetails Total
AdjustmentDetails Total
SoftCountDropDetails Total
CloserDetails Total
OpenerDetails Total
TransferDetails Total
(6 row(s) affected)
If you have many tables with computed columns and want to see the table names as well:
SELECT sys.objects.name, sys.computed_columns.name
from sys.computed_columns
inner join sys.objects on sys.objects.object_id = sys.computed_columns.object_id
order by sys.objects.name
Would any of you know how to get the list of computed columns in a SQL Server database table?
I found sys.sp_help tablename does return this information, but only in the second result-set.
I am trying to find out if there is a better way of doing this. Something which only returns a single result set.
Check the sys.columns system catalog view:
SELECT *
FROM sys.columns
WHERE is_computed = 1
This gives you all computed columns in this database.
If you want those for just a single table, use this query:
SELECT *
FROM sys.columns
WHERE is_computed = 1
AND object_id = OBJECT_ID('YourTableName')
This works on SQL Server 2005 and up.
UPDATE: There's even a sys.computed_columns system catalog view which also contains the definition (expression) of the computed column - just in case that might be needed some time.
SELECT *
FROM sys.computed_columns
WHERE object_id = OBJECT_ID('YourTableName')
If you want to use the INFORMATION_SCHEMA views, then try
SELECT
COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA+'.'+TABLE_NAME),COLUMN_NAME,'IsComputed')
AS IS_COMPUTED,
*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='<Insert Your Table Name Here>'
For SQL Server 2000 the syntax is:
SELECT * FROM sys.columns
WHERE is_computed = 1
And the slightly more useful:
SELECT
sysobjects.name AS TableName,
syscolumns.name AS ColumnName
FROM syscolumns
INNER JOIN sysobjects
ON syscolumns.id = sysobjects.id
AND sysobjects.xtype = 'U' --User Tables
WHERE syscolumns.iscomputed = 1
sample output:
TableName ColumnName
===================== ==========
BrinksShipmentDetails Total
AdjustmentDetails Total
SoftCountDropDetails Total
CloserDetails Total
OpenerDetails Total
TransferDetails Total
(6 row(s) affected)
If you have many tables with computed columns and want to see the table names as well:
SELECT sys.objects.name, sys.computed_columns.name
from sys.computed_columns
inner join sys.objects on sys.objects.object_id = sys.computed_columns.object_id
order by sys.objects.name
I'm collecting metadata using the sys.* views, and according to the documentation, the sys.identity_columns view will return the seed and increment values like so.
CREATE TABLE ident_test (
test_id int IDENTITY(1000,10),
other int
)
SELECT name, seed_value, increment_value
FROM sys.identity_columns
WHERE object_id = OBJECT_ID( 'ident_test' )
However, the above query just returns one column. Is it just me?
(Note: I've had to change this question somewhat from its earlier version.)
Shouldn't you reverse the from and join, like this:
SELECT c.name, i.seed_value, i.increment_value
from sys.identity_columns i
join sys.columns c
ON i.object_id = c.object_id
AND i.column_id = c.column_id
You are missing the Where clause. Your query is effectively saying 'Give me all of sys.columns and any matching rows from sys.identity_columns you have (but give me null if there are no matching rows)'.
By adding the Where clause below you'll change it to only return where an exact match is returned, which is the same as an inner join in this instance really.
SELECT
c.name, i.seed_value, i.increment_value
FROM
sys.columns c
LEFT OUTER JOIN sys.identity_columns i
ON i.object_id = c.object_id
AND i.column_id = c.column_id
Where I.seed_value is not null
So I think your data is correct, there are no results to view though.
Are you sure you are running this in a database with tables with IDENTITY columns?
SELECT c.name, i.seed_value, i.increment_value
FROM sys.columns c
INNER JOIN sys.identity_columns i
ON i.object_id = c.object_id
AND i.column_id = c.column_id
Returns rows for me in a regular production database with a few identities.
Using a LEFT JOIN returns these rows as well as many which are not IDENTITY
I ran this on another database, and I noticed some NULLs are returned (even in the INNER JOIN case). This is because some of the columns are in VIEWs.
Try adding:
INNER JOIN sys.tables t
ON t.object_id = c.object_id
To filter only to actual IDENTITY columns in tables.
your query returns what I'd expect [see below]; it returns the single meta-data row about the single identity column (test_ID) in table (ident_test), the oter column (other) has no meta-data in the sys.identity_column as is is not an identity.
SELECT name, seed_value, increment_value
FROM sys.identity_columns
WHERE object_id = OBJECT_ID( 'ident_test' )
select name, is_identity, is_nullable
from sys.columns
WHERE object_id = OBJECT_ID( 'ident_test' )
Which gives
name seed_value increment_value
-----------------------------------------
test_id 1000 10
(1 row(s) affected)
name is_identity is_nullable
-------------------------------------
test_id 1 0
other 0 1
(2 row(s) affected)