Why SQL Server not displaying sys.columns.object_id properly? - sql-server-2016

when I am only fetching sys.columns.object_id from sys.columns, it displays the below result:
select top 5 sys.columns.object_id as columns_object_id from sys.columns
columns_object_id
-----------
3
3
3
3
3
but when I am fetching the same column sys.columns.object_id after joining with sys.tables.object_id it displays the below result:
SELECT top 5
c.object_id as column_Object_id,
t.object_id as Table_Object_id
FROM
sys.columns as c
JOIN sys.tables as t ON
c.object_id = t.object_id
column_Object_id Table_Object_id
---------------- ---------------
114099447 114099447
114099447 114099447
114099447 114099447
114099447 114099447
114099447 114099447
Now i want to know why the columns.Object_id doesn't displaying like it displaying in join query?

There are a couple of things going on here.
First, sys.tables only has information about user tables. The object_id you're seeing in your first query is a system table, so that will get filtered off by your join.
Also, tables in SQL Server are unordered sets of data, and TOP(n) has no meaning without an accompanying ORDER BY. So that's part of it, too.
Try these variations to see what I mean. I obviously have different user tables than you do, so the results I get are meaningless to you, but you'll see the difference between them on your system:
SELECT --Returns 3 for me, too.
TOP 5
OBJECT_NAME(object_id)
,c.object_id as columns_object_id
FROM
sys.columns AS c;
SELECT --Returns the first user table's data.
TOP 5
OBJECT_NAME(c.object_id) AS ObjectName
,c.object_id as column_Object_id
,t.object_id as Table_Object_id
FROM
sys.columns AS c
JOIN
sys.tables AS t
ON
c.object_id = t.object_id;
And now try this one, noting the ORDER BY and the LEFT JOIN, since the system table that we're looking for isn't on the table sys.tables:
SELECT
TOP 5
OBJECT_NAME(c.object_id) AS ObjectName
,c.object_id as column_Object_id
,t.object_id as Table_Object_id
FROM
sys.columns AS c
LEFT JOIN
sys.tables AS t
ON
c.object_id = t.object_id
ORDER BY c.object_id

Related

Fetching of the Columns and Rows using Database name over Schema Name

I am trying to achieve finding the number of rows in a given column, I understand that we can achieve that by doing something like
SELECT DISTINCT s.name as SchemaName,OBJECT_NAME(o.OBJECT_ID) AS TableName,p.row_count
FROM
SYS.objects o JOIN SYS.schemas s
ON o.schema_id=s.schema_id
JOIN sys.dm_db_partition_stats p
ON o.object_id=p.object_id
WHERE o.type LIKE 'U'
AND s.name LIKE '%dbo%' -- schema name
ORDER BY TableName
However I could not find a join between the Sys.Databases and the aforementioned query. Suggestions? Or is there any efficient way to achieve the same?

SQL to find the number of rows per table in a database

My goal is to create a spreadsheet of all the tables in the current database that will display the table name and the number of rows in each table. A bonus would be to also be able to display when anything was last entered or changed in the table. I'm not sure if the last part is possible though.
This is what I have so far... its nothing much but I just can't beat my head around how to add the per table row count to it.
SELECT name, type, type_desc
FROM [scheme].sys.all_objects
WHERE type = 'U'
You can use this query against the system catalog views:
SELECT
t.NAME AS TableName,
p.rows AS RowCounts
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, p.Rows
ORDER BY
t.Name
to get the desired result - all tables in the current database, and the number of rows in each.
CREATE TABLE #T
(TABLENAME VARCHAR(100) ,
COUNT INT)
INSERT INTO #T
EXEC SP_MSFOREACHTABLE 'SELECT ''?'' ,COUNT(*) FROM ?'
SELECT * FROM #T
DROP TABLE #T

How to discover to which table\field is linked the foreign key of a table?

I am pretty new in Microsoft SQL server and I am not much into databases.
I have the following doubt:
On my database I have a table named CPE
This table have a field (a column) named SourceId that is the FOREIGN KEY of my table.
So I think that this field have to contain the value definied in some field of another table because it binds together 2 tables).
What have I to do to discover what is the other field and the other table which is linked to?
Tnx
Andrea
You are looking for certainly:
sp_help [table_name]
or try this query:
select t.name as ForeignKeytable, fk.constraint_column_id as ForeignKey_No, c.name as ForeignKeyColumn
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where fk.referenced_object_id = (select object_id from sys.tables where name = 'name')
order by ForeignKeytable, ForeignKey_No
Try this
Method 1 :
SELECT
object_name(parent_object_id) ParentTableName,
object_name(referenced_object_id) RefTableName,
name
FROM sys.foreign_keys
WHERE parent_object_id = object_id('Tablename')
Or:
Method 2 :
SELECT
OBJECT_NAME(f.parent_object_id) TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM
sys.foreign_keys AS f
INNER JOIN
sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN
sys.tables t
ON t.OBJECT_ID = fc.referenced_object_id
WHERE
OBJECT_NAME (f.referenced_object_id) = 'Tablename'
In Object Explorer, right-click the table that will be on the foreign-key side of the relationship and click Design.
The table opens in Table Designer.
From the Table Designer menu, click Relationships.
The relationship appears in the Selected Relationship list with a system-provided name in the format FK__, where tablename is the name of the foreign key table.
Click the relationship in the Selected Relationship list.
Click Tables and Columns Specification in the grid to the right and click the ellipses (…) to the right of the property.
Now, you will be able to see relationship of that table with other tables.

Calculate the maximum storage size of table record?

Is there a way to determine what the maximum size of a record would be in SQL Server past doing it by hand? For example:
CREATE TABLE test (
id INT PRIMARY KEY IDENTITY(1, 1),
name VARCHAR(256),
test_date DATETIME
)
so, if I'm not mistaken, when calculating that by hand that record could be a maximum of 272 bytes. However, I have a table with a lot more columns than that, and I need to do this for more than one table, so I wanted to know if I could do this with a simple query.
I can't find any information in INFORMATION_SCHEMA.TABLES or even INFORMATION_SCHEMA.COLUMNS where I figured I could do a simple SUM for example. Further, sysobjects and syscolumns don't seem to have the necessary information. The syscolumns table does have a length field but that's not the actual storage size.
Thanks all!
Try this:
Select schema_name(T.schema_id) As SchemaName,
T.Name As TableName,
Sum(C.max_length) As RowSize
From sys.tables T
Inner Join sys.columns C
ON T.object_id = C.Object_ID
INNER JOIN sys.types S
On C.system_type_id = S.system_type_Id
Group By schema_name(T.schema_id),
T.Name
Order By schema_name(T.schema_id),
T.Name

How to identify all stored procedures referring a particular table

I created a table on development environment for testing purpose and there are few sp's which are refreing this table. Now I have have to drop this table as well as identify all sp's which are referring this table. I am facing difficulty to find list of all sp's. Please suggest some query by assuming that the table name is 'x' and database is sql server 2005.
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%TableNameOrWhatever%'
BTW -- here is a handy resource for this type of question: Querying the SQL Server System Catalog FAQ
The following works on SQL2008 and above. Provides a list of both stored procedures and functions.
select distinct [Table Name] = o.Name, [Found In] = sp.Name, sp.type_desc
from sys.objects o inner join sys.sql_expression_dependencies sd on o.object_id = sd.referenced_id
inner join sys.objects sp on sd.referencing_id = sp.object_id
and sp.type in ('P', 'FN')
where o.name = 'YourTableName'
order by sp.Name
sometimes above queries will not give correct result, there is built in stored procedure available to get the table dependencies as:
EXEC sp_depends #objname = N'TableName';
A non-query way would be to use the Sql Server Management Studio.
Locate the table, right click and choose "View dependencies".
EDIT
But, as the commenters said, it is not very reliable.
In management studio you can just right click to table and click to 'View Dependencies'
than you can see a list of Objects that have dependencies with your table :
The following query will fetch all Stored Procedure names and the corresponding definition of those SP's
select
so.name,
text
from
sysobjects so,
syscomments sc
where
so.id = sc.id
and UPPER(text) like '%<TABLE NAME>%'
SELECT
o.name
FROM
sys.sql_modules sm
INNER JOIN sys.objects o ON
o.object_id = sm.object_id
WHERE
sm.definition LIKE '%<table name>%'
Just keep in mind that this will also turn up SPs where the table name is in the comments or where the table name is a substring of another table name that is being used. For example, if you have tables named "test" and "test_2" and you try to search for SPs with "test" then you'll get results for both.
The query below works only when searching for dependencies on a table and not those on a column:
EXEC sp_depends #objname = N'TableName';
However, the following query is the best option if you want to search for all sorts of dependencies, it does not miss any thing. It actually gives more information than required.
select distinct
so.name
--, text
from
sysobjects so,
syscomments sc
where
so.id = sc.id
and lower(text) like '%organizationtypeid%'
order by so.name
SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'table_name' + '%'
GO
This will work if you have to mention the table name.
You have basically 2 options:
----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'
These 2 queries will get you all the stored procedures that are referring the table you desire. This query relies on 2 sys tables which are sysobjects and syscomments. The sysobjects is where all of your DB object names are stored this includes the stored procedures.
The syscomments contains the text for all of your procedures.
If you query:
SELECT * FROM syscomments
You'll have a table containing the id which is the mapping to the sysobjects table with the text contained in the stored procedures as the last column.
This useful query also works if you are using Azure SQL / Synapse Anlaytics
SELECT DISTINCT o.name AS Object_Name,o.type_desc
FROM sys.sql_modules m
INNER JOIN sys.objects o
ON m.object_id=o.object_id
WHERE m.definition Like '%Table_Name%'
Try This
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%your table name%'
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'