I am searching for a query/proceduer that give me all the dependecies of a procedure (results similar to sp_depends)
example in procedure proc1 , it execute proc2,proc3,
in procedure proc2 , it execute xproc1, xproc2
so I want my output to be like
proc1 -> proc2 -> xproc1 ->xproc2
proc1 -> proc3
EDIT:
I have created the below procedure , but the problem about them it gave me the below error
------------------------ Execute ------------------------
Maximum stored procedure nesting level exceeded (limit 60). Please use sp_configure to increase the 'max nesting level'.
return status = -6
Also the after after limiting the count on the cursor ( If your read carefuly the procedure , youll notice count , so I modified the procedure later to specify how many nest I got to avoide the error and I did avoid it ) the result is missing , I didnt get all the procedure dependency , what I am saying I am not getting all the procedure dependencies , I though problem with the procedure after investigating and checking into syscomments and selecting in depends sysdepends it seems sybase doenst give all the dependency . I dont know. Do you have a way that can help me got all the dependency ?
CREATE TABLE dbo.PROC_HIERARCHY
( PROC_PATH VARCHAR(4000) NULL
)
GO
CREATE PROCEDURE dbo.PROC_DEP_REC
#PROC_ID INTEGER,
#PATH VARCHAR(4000) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #CURR_ID INTEGER
DECLARE #CURR_NAME VARCHAR(40)
DECLARE #ROW_COUNT NUMERIC(12)
DECLARE #PATH_OUT VARCHAR(4000)
-- retrieve the children
DECLARE CURS CURSOR FOR
select distinct o2.name, o2.id
from sysdepends d
inner join sysobjects o
on d.id = o.id
inner join sysobjects o2
on d.depid = o2.id
where o.type = 'P'
and o2.type = 'P'
and o.id = #PROC_ID
OPEN CURS
FETCH CURS INTO #CURR_NAME, #CURR_ID
WHILE (##SQLSTATUS <> 2)
BEGIN
SELECT #PATH_OUT = #PATH + #CURR_NAME + '/'
select #ROW_COUNT = COUNT(1)
from sysdepends d
inner join sysobjects o
on d.id = o.id
inner join sysobjects o2
on d.depid = o2.id
where o.type = 'P'
and o2.type = 'P'
and o.id = #CURR_ID
IF (#ROW_COUNT > 0)
EXEC PROC_DEP_REC #CURR_ID, #PATH_OUT OUTPUT
ELSE
BEGIN
IF (RIGHT(#PATH_OUT, 1) = '/')
SELECT #PATH_OUT = LEFT(#PATH_OUT, LEN(#PATH_OUT) - 1)
INSERT INTO PROC_HIERARCHY VALUES (#PATH_OUT)
END
FETCH CURS INTO #CURR_NAME, #CURR_ID
END
CLOSE CURS
DEALLOCATE CURS
IF (RIGHT(#PATH_OUT, 1) = '/')
SELECT #PATH = SUBSTRING(#PATH_OUT, 1, LEN(#PATH_OUT) - CHARINDEX('/', REVERSE(#PATH_OUT)))
END
GO
CREATE PROCEDURE dbo.PROC_DEP
AS
BEGIN
SET NOCOUNT ON
DECLARE #CURR_ID INTEGER
DECLARE #CURR_NAME VARCHAR(40)
DECLARE #PATH VARCHAR(4000)
DECLARE CURS CURSOR FOR
select distinct o.name, o.id
from sysdepends d
inner join sysobjects o
on d.id = o.id
inner join sysobjects o2
on d.depid = o2.id
where o.type = 'P'
and o2.type = 'P'
OPEN CURS
FETCH CURS INTO #CURR_NAME, #CURR_ID
WHILE (##SQLSTATUS <> 2)
BEGIN
SELECT #PATH = #CURR_NAME + '/'
EXEC PROC_DEP_REC #CURR_ID, #PATH OUTPUT
FETCH CURS INTO #CURR_NAME, #CURR_ID
END
CLOSE CURS
DEALLOCATE CURS
SELECT DISTINCT *
FROM PROC_HIERARCHY
ORDER BY PROC_PATH
END
GO
What about the queries in sp_depends itself?
Go to the $SYBASE/ASE-X_Y/scripts directory and find the installmaster file (or instmstr on WIndows) and look for sp_depends.
Then you just need to format the output a bit differently, for exmaple by running a cursor loop over the final result set.
Related
This query was from a 2017 post on this site and the results fit my requirements but I need them to a temp table. It currently writes to the screen with the column headers from each table and the values in each. When I try and insert it onto a temp table I can't get the column names, only the values. Basically I'm comparing two tables and need to report the differences in them. Your assistance is greatly appreciated.
DECLARE #ColName varchar(100)
DECLARE #Table1 varchar(100) = 'MyTable'
DECLARE #Table2 varchar(100) = 'MyOtherTable'
IF (OBJECT_ID('tempdb..#col') IS NOT NULL) DROP TABLE #col
SELECT IDENTITY(INT, 1, 1) RowNum , c.name
INTO #col
FROM SYS.Objects o
JOIN SYS.columns c on o.object_id = c.object_id
WHERE o.name = #Table1 AND NOT c.Name IN ('List','Columns','YouWantToIgnore')
DECLARE #Counter INT = (SELECT MAX(RowNum) FROM #col)
WHILE #Counter > 0
BEGIN
SET #ColName = (SELECT name FROM #Col WHERE RowNum= #Counter)
EXEC ('SELECT t1.Identifier
,t1.'+#ColName+' AS '+#Table1+#ColName+'
,t2.'+#ColName+' AS '+#Table2+#ColName+'
FROM '+#Table1+' t1
LEFT JOIN '+#Table2+' t2 ON t1.Identifier = t2.Identifier
WHERE t1.'+#ColName+' <> t2.'+#ColName)
SET #Counter = #Counter - 1
END
I'm using SQL Server 2012 and have written a stored procedure that calculates table statistics using the sys tables. I realize there are reports in SSMS that do this for you, however, I'm wanting additional information. It seems like I'm forced to use dynamic SQL to make this happen, but it seems slow and clunky. My stored procedure works, but I was curious there a more efficient way to write the query, maybe even without dynamic SQL?
DECLARE #my_cursor CURSOR,
#sql nvarchar(250), #table_name nvarchar(100),
#days_loaded int, #row_count int, #row_count_per_day int,
#used_mb numeric(36,2), #used_mb_per_day numeric(36,2),
#first_date_loaded date, #last_date_loaded date,
#expected_first_date date, #gaps_exist nvarchar(1)
-- Delete temp table #tables in case the stored procedure is ran twice in the same session
IF OBJECT_ID('tempdb.dbo.#tables', 'U') IS NOT NULL
DROP TABLE #tables
-- Select all the tables and stats from the dallas schema into a temp table
SELECT
s.name + '.' + t.name AS table_name,
p.rows AS row_count,
CAST(ROUND(SUM(a.used_pages) / 128.00, 2) AS NUMERIC(36, 2)) AS used_mb
INTO
#tables
FROM
sys.tables AS t
INNER JOIN
sys.indexes AS i ON t.object_id = i.object_id
INNER JOIN
sys.partitions AS p ON i.object_id = p.object_id AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units AS a ON p.partition_id = a.container_id
INNER JOIN
sys.schemas AS s ON t.schema_id = s.schema_id
WHERE
s.name = 'dallas'
GROUP BY
t.name, s.name, p.rows
-- Add some additional fields in the temp table to be used for population in loop below
ALTER TABLE #tables ADD days_loaded INT NULL
ALTER TABLE #tables ADD used_mb_per_day numeric(36,2) NULL
ALTER TABLE #tables ADD row_count_per_day INT NULL
ALTER TABLE #tables ADD first_date_loaded DATE NULL
ALTER TABLE #tables ADD expected_first_date DATE NULL
ALTER TABLE #tables ADD gaps_exist nvarchar(1) NULL
-- Loop through each table in dallas schema
BEGIN
SET #my_cursor = CURSOR FOR SELECT table_name, row_count, used_mb FROM #tables
OPEN #my_cursor
FETCH NEXT FROM #my_cursor INTO #table_name, #row_count, #used_mb
WHILE ##FETCH_STATUS = 0
BEGIN
-- Calculate first date that was loaded to see history of how far back table goes
SET #sql = N'SELECT TOP 1 #first_date_loaded = CONVERT(date,Min(data_load_timestamp)) FROM ' + #table_name
EXECUTE sp_executesql #sql, N'#first_date_loaded date OUTPUT', #first_date_loaded=#first_date_loaded OUTPUT
-- Calculate last date that was loaded to offset expected first date if needed (data that is loaded day of instead of day before)
SET #sql = N'SELECT TOP 1 #last_date_loaded = CONVERT(date,Max(data_load_timestamp)) FROM ' + #table_name
EXECUTE sp_executesql #sql, N'#last_date_loaded date OUTPUT', #last_date_loaded=#last_date_loaded OUTPUT
-- Calculate days loaded by retrieving count of distinct dates in table
SET #sql = N'SELECT #days_loaded=COUNT(*) FROM (SELECT DISTINCT CONVERT(date, data_load_timestamp) AS data_load_date FROM ' + #table_name + ') tt'
EXECUTE sp_executesql #sql, N'#days_loaded int OUTPUT', #days_loaded=#days_loaded OUTPUT
IF #days_loaded <> 0
BEGIN
SET #row_count_per_day = #row_count / #days_loaded
SET #used_mb_per_day = #used_mb / #days_loaded
SET #expected_first_date = DATEADD(d,#days_loaded * -1,GETDATE())
IF #last_date_loaded = CONVERT(date,GETDATE()) SET #expected_first_date = DATEADD(d,1,#expected_first_date)
IF #first_date_loaded = #expected_first_date
SET #gaps_exist = 'N'
ELSE
SET #gaps_exist = 'Y'
END
-- Update temp table with additional fields that were calculated
SET #sql = N'UPDATE #tables SET days_loaded=' + CONVERT(nvarchar,#days_loaded) +
', row_count_per_day=' + CONVERT(nvarchar, #row_count_per_day) +
', used_mb_per_day=' + CONVERT(nvarchar,#used_mb_per_day) + ', first_date_loaded=''' +
CONVERT(nvarchar,#first_date_loaded) + ''', expected_first_date=''' +
CONVERT(nvarchar,#expected_first_date) + ''', gaps_exist=''' + #gaps_exist + ''' WHERE table_name=''' + #table_name + ''''
EXECUTE sp_executesql #sql
FETCH NEXT FROM #my_cursor INTO #table_name, #row_count, #used_mb
END
CLOSE #my_cursor
DEALLOCATE #my_cursor
END
-- Final return showing results from temp table sorted by largest utilization first
SELECT * FROM #tables ORDER BY used_mb DESC
Ive been struggling with this one for a while and appreciate any help.
I have a table that continuously get updated with a list of table names (same table can occure several times) that has been updated with new data recently in Database 1.
I want to create a query that checks this update list and inserts the data from updated tables in Database 1, into corresponding tables in Database 2. And loops through until the end of the list.
The list can look like this:
ID Table TimeStamp
----------------------- -------- -----------------------
0313778E-CB68-E811-910D Customer 2018-07-10 13:27:28.567
0313778E-CB68-E811-910D Customer 2018-07-10 13:28:58.010
194DD17A-CE68-E811-910D Order 2018-07-10 13:27:28.567
0EBB391D-126B-E811-910D Product 2018-07-10 13:28:58.010
4AAE33A5-CE68-E811-910D Customer 2018-07-10 13:27:28.567
DFA2A68C-056B-E811-910D Order 2018-07-10 13:28:58.010
C2CFECB6-CE68-E811-910D Employee 2018-07-10 13:27:28.583
To make it worse, the tables in Database 2 don't have same amount of columns as Database 1.
Ive been working on both MERGE and Cursor, as well as dynamic SQL. Im new to these so keep getting stuck. I think dynamic SQL + CURSOR is the best way to go. All of this will result in a stored procedure. Maybe there is a better way of doing it? Anyway, this is what I have:
Declare #Source_TableName_Column --this one contains the Database 1 tables as well as the correct columns needed to fill matching table in Database 2.
Declare #InsertInto NVARCHAR(MAX),
#TargetTable NVARCHAR(MAX)='Select name from Database2.sys.all_objects', --list of tables I have in Database 2
#Columns NVARCHAR(MAX) = 'Select name from Database2.sys.all_columns', --list of columns I have in Database 2 (same names as it is in SourceTable in Database 1)
;
DECLARE TableInsert CURSOR FOR
SELECT distinct SourceTableName from Database3.dbo.UpdateTableList
OPEN TableInsert
FETCH NEXT FROM TableInsert
INTO #TableName
--LOOP
WHILE ##FETCH_STATUS=0
BEGIN
SET #InsertInto = 'insert into Database2.dbo.'+#TargetTable+' '+(#Columns)+' values'+(....)+'' --not sure how to do this variable where i get all the results from SourceTable matching columns in TargetTable in database 2
FETCH NEXT FROM TableInsert
INTO #TableName
END
--CLOSE CURSOR
CLOSE TableInsert
DEALLOCATE TableInsert
This is complex. I would approach it in a simpler fashion than what you are doing. I’d do it your way if scenario involved destination tables with the same schema, but numerous columns, which does not seem to be the case with you.
Here’s what i’d do.
Open cur1
Fetch next from cur1 into #tablename ....
While ##fetchstatus = 0
Begin
If ##tablename= ‘tbl1’
Begin
Insert into database2.dbo.tbl2 values
Select ... from database1.dbo.table1 where ..
End
If ##tablename = ‘tblx’
And so on
Fetch next from cur1 into ...
End
I made a solution that works for me. Some names I have changed here to better fit my description above. I think they are correct, will look through it later and correct it if wrong =)
I am, however, a bit unsure about the delete statement further down in the code.
I have a TempTable based on the update list. I want to delete the rows in the update list after Ive inserted into tables. I have one with two 'where field IN (corresponding field in TempTable' clauses and another one with a 'delete from ... where exists (tempTable). Temptable has two columns but update list has three in total. Whichever is fastest/best?
DECLARE #InsertInto NVARCHAR(MAX);
DECLARE #SourceID NVARCHAR(MAX);
DECLARE #TableAttribute NVARCHAR(MAX);
DECLARE #SourceViewName NVARCHAR(MAX);
DECLARE #TargetTable NVARCHAR(MAX);
DECLARE #SourceTableName NVARCHAR(MAX);
/*-------Create temp table to be used in cursor-------*/
Declare #SQL_TempTable_Insert NVARCHAR(MAX);
IF OBJECT_ID('tempdb..#Cursor_TempTable') IS NOT NULL DROP TABLE #Cursor_TempTable
CREATE TABLE #Cursor_TempTable (
SourceEntity NVARCHAR(MAX) )
/*-------variable to be used in insert step below-------*/
SET #SQL_TempTable_Insert = 'SELECT SourceLogicalName FROM DataBaseC.dbo.REF_ENTITIES_SYNC group by SourceLogicalName'
/*-------Insert into temp table-------*/
INSERT INTO #Cursor_TempTable EXECUTE (#SQL_TempTable_Insert)
/*-------Create temp table from NeworUpdate table-------*/
Declare #SQL_TempTable_NewOrUpdated NVARCHAR(MAX);
IF OBJECT_ID('tempdb.. #TempTable_NewOrUpdated') IS NOT NULL DROP TABLE #TempTable_NewOrUpdated
CREATE TABLE #TempTable_NewOrUpdated (
[ID] NVARCHAR(MAX),
[TimeStamp] DATETIME )
/*-------variable to be used in insert step below in NewOrUpdate temp table-------*/
SET #SQL_TempTable_NewOrUpdated = 'SELECT ID, TimeStamp FROM DataBaseC.dbo.[REF_POSTS_NewOrUpdated] group by ID, TimeStamp'
/*-------Insert into NewOrUpdate temp table-------*/
INSERT INTO #TempTable_NewOrUpdated EXECUTE (#SQL_TempTable_NewOrUpdated)
/*-------Cursor segment-------*/
DECLARE EntitiesInsert CURSOR FOR
SELECT SourceEntity FROM #Cursor_TempTable
OPEN EntitiesInsert
FETCH NEXT FROM EntitiesInsert
INTO #TargetTable
--LOOP
WHILE ##FETCH_STATUS=0
BEGIN
BEGIN TRY
BEGIN TRAN
SET #SourceViewName = (select SourceName from DataBaseC.dbo.REF_ENTITIES_SYNC where Targetname = #TargetTable);
SET #SourceTableName = (select SourceTableName from DataBaseC.dbo.REF_ENTITIES_SYNC where Targetname = #TargetTable);
SET #TableAttribute = stuff(( select ', ' +char(10)+ ac.[name] from DataBaseB.sys.all_columns ac
inner join DataBaseB.sys.all_objects ao on ao.object_id=ac.object_id
where ao.name = #TargetTable and ac.name not in ('ValidFrom','ValidTo')
FOR XML PATH('')
), 1, 1, '')
--Finds DatabaseA table's Primary Key
SET #SourceID = (select c.name
from sys.index_columns ic
inner join sys.columns c on ic.object_id = c.object_id and ic.column_id = c.column_id
inner join sys.indexes i on ic.object_id = i.object_id and ic.index_id = i.index_id
inner join sys.tables t on i.object_id = t.object_id
inner join sys.schemas s on t.schema_id = s.schema_id
where i.is_primary_key= 1 and t.name = #SourceTableName);
SET #InsertInto = 'INSERT INTO DataBaseB.dbo.'+#TargetTable+' ('+#TableAttribute+')
SELECT '+#TableAttribute+' FROM DataBaseA.dbo.'+#SourceViewName+'
where '+#SourceID+' in (select nu.ID from DataBaseC.Inno.REF_ENTITIES_SYNC sync inner join #TempTable_NewOrUpdated nu on nu.SourceEntity = sync.TargetName where sync.TargetName = '''+#TargetTable+''' group by nu.ID )'
EXEC sp_sqlexec #insertInto
--Delete the records from [DataBaseC].[dbo].[REF_POSTS_NewOrUpdated] that we have inserted.
--DELETE FROM [DataBaseC].[dbo].[REF_POSTS_NewOrUpdated]
-- WHERE ID = (select [ID] from #TempTable_NewOrUpdated)
-- AND TimeStamp = (select [Timestamp] from #TempTable_NewOrUpdated)
----alt2
--DELETE FROM [DataBaseC].[dbo].[REF_POSTS_NewOrUpdated]
-- where exists (select * from #TempTable_NewOrUpdated)
--End TRAN
COMMIT
--End TRY
END TRY
--Catch possible errors
BEGIN CATCH
--IF there is an open transaction then roll back and print error messages.
IF ##TRANCOUNT > 0
ROLLBACK TRANSACTION
DECLARE #ErrorNumber INT = ERROR_NUMBER();
DECLARE #ErrorLine INT = ERROR_LINE();
DECLARE #ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
DECLARE #ErrorSeverity INT = ERROR_SEVERITY();
DECLARE #ErrorState INT = ERROR_STATE();
PRINT 'Actual error number: ' + CAST(#ErrorNumber AS VARCHAR(10));
PRINT 'Actual line number: ' + CAST(#ErrorLine AS VARCHAR(10));
PRINT 'Actual error message: ' + CAST(#ErrorMessage AS VARCHAR(MAX));
PRINT 'Actual error Severity: ' + CAST(#ErrorSeverity AS VARCHAR(MAX));
PRINT 'Actual error State: ' + CAST(#ErrorState AS VARCHAR(MAX));
END CATCH
FETCH NEXT FROM EntitiesInsert
INTO #TargetTable
END
CLOSE EntitiesInsert
DEALLOCATE EntitiesInsert
GO
I have a trigger like below on user table to insert into the audit table with which column was updated and previous value:
ALTER TRIGGER [dbo].[trgAfterUpdate] ON [dbo].[tbl_User]
AFTER UPDATE
AS
declare #fieldname varchar(128) ;
declare #OldValue varchar(255);
declare #CreateUser varchar(100) ;
declare #User_Key int;
select #CreateUser =i.user_name from deleted i;
SELECT #User_Key = i.user_key from inserted i;
if update(user_name)
begin
select #OldValue=j.user_name from deleted j;
set #fieldname = 'user_name';
insert into tbl_Audit(user_key, field_name, previuos_Value, user_name)
values(#User_Key ,#fieldname,#OldValue, #CreateUser);
end
But my questions is I have like 100 fields on my table. I can't write 100 if conditions. And i need a suggestion how to use while loop in it, and how is it going to effect the performance.
Thanks
Try this one -
ALTER TRIGGER [dbo].[trgAfterUpdate]
ON [dbo].[tbl_User]
AFTER UPDATE
AS BEGIN
SET NOCOUNT ON
SET XACT_ABORT ON
DECLARE #DocumentUID UNIQUEIDENTIFIER
DECLARE cur CURSOR FORWARD_ONLY READ_ONLY LOCAL FOR
SELECT DocumentUID, ...
FROM INSERTED
OPEN cur
FETCH NEXT FROM cur INTO #DocumentUID, ...
WHILE ##FETCH_STATUS = 0 BEGIN
DECLARE
#BeforeChange XML
, #AfterChange XML
SELECT #BeforeChange = (
SELECT *
FROM DELETED
WHERE [DocumentUID] = #DocumentUID
FOR XML RAW, ROOT
)
, #AfterChange = (
SELECT *
FROM INSERTED
WHERE [DocumentUID] = #DocumentUID
FOR XML RAW, ROOT
)
INSERT INTO dbo.LogUser (DocumentUID, BeforeChange, AfterChange)
SELECT #DocumentUID, #BeforeChange, #AfterChange
-- your business logic
FETCH NEXT FROM cur INTO #DocumentUID, ...
END
CLOSE cur
DEALLOCATE cur
END
Try using query similar to this one – it will generate If statements for all columns of a given table.
Note: This is not fully tested and probably needs more adjustments but you see the idea behind it.
select 'if update(' + C.name + ')
begin
select #OldValue=j.' + C.name + ' from deleted j;
set #fieldname = ''' + C.name + ''';
insert into tbl_Audit(user_key, field_name, previuos_Value, user_name)
values(#User_Key ,#fieldname,#OldValue, #CreateUser);
end'
from sys.all_columns C
inner join sys.tables T on C.object_id = T.object_id
where T.name = 'table_name' and T.schema_id = SCHEMA_ID('schema_name')
If wouldn’t go with while loop because it can probably cause perf issues…
SNAHi
anyone please suggest a query in sql to find the unused tables.
I have a legacy application migrated to .net from coldfusion.But lots of tables are unused now
What is the best way to find all the unused objects from database. (sql 2005)
thanks
SNA
In SQL Server, the acutal table data IS the clustered index. Using this query on the Dynamic Management Views (DMV) in SQL Server 2005 and up, you can find unused indices - if you find any clustered index (index_id=1) being unused over an extended period of time, the table is not being used anymore:
DECLARE #dbid INT
SELECT #dbid = DB_ID(DB_NAME())
SELECT
OBJECTNAME = OBJECT_NAME(I.OBJECT_ID),
INDEXNAME = I.NAME,
I.INDEX_ID
FROM
SYS.INDEXES I
JOIN
SYS.OBJECTS O ON I.OBJECT_ID = O.OBJECT_ID
WHERE
OBJECTPROPERTY(O.OBJECT_ID, 'IsUserTable') = 1
AND I.INDEX_ID NOT IN
(SELECT S.INDEX_ID
FROM SYS.DM_DB_INDEX_USAGE_STATS S
WHERE S.OBJECT_ID = I.OBJECT_ID
AND I.INDEX_ID = S.INDEX_ID
AND DATABASE_ID = #dbid)
ORDER BY
OBJECTNAME,
I.INDEX_ID,
INDEXNAME ASC
Another option would be to temporarily rename a table if you suspect it's not being used, and then see if your app(s) still work as expected. If they do for e.g. 30 days or so, then you're pretty sure you don't need that table anymore.
Marc
-- Query to find the tables not used by any stored procedure, function nor view
-- Using SQL 2005 system tables, all programatical objects for dependencies, and one&only query:
select tables.name, progr.name
from sys.objects tables (nolock)
left join sys.syscomments comm (nolock) on comm.text like '%' + tables.name +'%'
left join sys.objects progr (nolock) on progr.object_id = comm.id and progr.type in ('P', 'FN', 'TR', 'V' )
where tables.type = 'U'
and comm.id is null
Here is a query i have written to find the tables not used by any store procedures..
......................................................................................
Declare #tablename nvarchar(40)
Declare tablecursor cursor for
Select name from sysobjects where xtype = 'U'
DECLARE #sqlCommand nvarchar(1000)
declare #rowCount int
DECLARE #searchstring varchar(50)
DECLARE #ParmDefinition nvarchar(500);
create table #temp
(
UnusedTables nvarchar(40)
)
open tablecursor
fetch next from tablecursor into #tablename
while ##fetch_status = 0
begin
set #searchstring='p'
SET #sqlCommand = N'SELECT #rows = count(o.name) from sysobjects o ,
syscomments c where o.type='+char(39)+#searchstring + char(39)+' and
o.id=c.id and c.text like '+ char(39)+'%' + #tablename +'%'+char(39);
SET #ParmDefinition = N'#rows int OUTPUT';
EXECUTE sp_executesql #sqlCommand, #ParmDefinition,#rows=#rowCount OUTPUT;
if #rowCount = 0
begin
insert into #temp values (#tablename)
end
fetch next from tablecursor into #tablename
end
close tablecursor
deallocate tablecursor
select UnusedTables from #temp
drop table #temp
thanks
SA
Try something like below
DECLARE #TableNameTemp TABLE
(
id INT IDENTITY (1, 1),
tablename VARCHAR(1000)
)
INSERT INTO #TableNameTemp
SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
ORDER BY table_name
DECLARE #CursorTestID INT = 1;
DECLARE #TotalCount INT = (SELECT Count(1)
FROM #TableNameTemp)
DECLARE #FinalResult TABLE
(
unsedtables VARCHAR(max)
)
DECLARE #TemExecInsert TABLE
(
testvalue VARCHAR(max),
type VARCHAR(max)
)
DECLARE #TableaName VARCHAR(max) = ''
WHILE #CursorTestID <= #TotalCount
BEGIN
DELETE FROM #TemExecInsert
SET #TableaName = (SELECT tablename
FROM #TableNameTemp
WHERE id = #CursorTestID)
INSERT INTO #TemExecInsert
EXEC Sp_depends
#objname = #TableaName
SET #CursorTestID = #CursorTestID + 1
IF ( (SELECT Count(1)
FROM #TemExecInsert) = 0 )
BEGIN
INSERT INTO #FinalResult
VALUES (#TableaName)
END
END
SELECT *
FROM #FinalResult
PS: Sorry, I am not certain how to bring the answer in shape. Hope this helps