if statement in transact sql - sql

I have a stored procedure that I need to enhance. This is what I have now.
ALTER PROCEDURE [rw].[sp_EFT_NoticeXLS2]
(#Scope varchar(50)
, #AcctPeriod char(6)
, #CompanyID nchar(10))
AS ......
What I need to do is to pass a variable #GLsubacct to it only if #CompanyID is 0000.
I tried.....
ALTER PROCEDURE [rw].[sp_EFT_NoticeXLS2]
(#Scope varchar(50)
, #AcctPeriod char(6)
, #CompanyID nchar(10)
IF (#CompanyID IS 0000)
#GLsubacct varchar(1000))
AS ....
but I am getting an error. I am not sure how to write the if statement. I need all the help I can get, thanks!

You can't do that.
You can setup the second variable to be "nullable"...making it "optional".
Then you can raise an exception if the rules don't follow.
Generic example:
Use Northwind
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[uspDoSomething]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[uspDoSomething]
GO
CREATE PROCEDURE [dbo].[uspDoSomething]
(
#CustomerId varchar(12)
, #PostalCode varchar(12) = NULL
)
AS
SET NOCOUNT ON;
if #CustomerId = 'ALFKI' AND #PostalCode IS NULL
BEGIN
THROW 51000, 'You must supply a Postal Code with this #CustomerId.', 1;
END
select * from dbo.Customers c
where
c.CustomerID = #CustomerId
AND
( #PostalCode IS NULL OR c.PostalCode = #PostalCode )
GO
/* examples */
exec [dbo].[uspDoSomething] 'ALFKI' , '12209'
exec [dbo].[uspDoSomething] 'ALFKI'
exec [dbo].[uspDoSomething] 'ANATR' , '05021'

You may not need to use the IF statement below depending on what your Stored Procedure actually does, however what you're looking for is probably something like this:
ALTER PROCEDURE [rw].[sp_EFT_NoticeXLS2]
#Scope varchar(50),
#AcctPeriod char(6),
#CompanyID nchar(10),
#GLsubacct varchar(1000) = NULL
AS
BEGIN
IF #CompanyID = '0000'
BEGIN
-- CompanyID is 0000
END
ELSE
BEGIN
-- CompanyID is NOT 0000
END
END
GO

Related

Stored procedure unsure syntax

I am trying to create a stored procedure that will determine if my customerid exists if it exists then my other parameter foundcustomer will be assigned to found otherwise not found. I am unsure how to assign found please help
here is what i tried
CREATE PROCEDURE procedure4
-- Add the parameters for the stored procedure here
#FoundCustomer varchar(10) = null,
#Customerid varchar (5) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
if Not(#Customerid is null)
SELECT customerid
from customers
where customerid = #Customerid
END
GO
Gordon is right, it sounds like you may want a function but if it has to be a stored procedure you can follow this example.
CREATE PROCEDURE procedure4
#Customerid varchar(5) = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FoundCustomer varchar(10) = ''
IF #FoundCustomer is not null
BEGIN
IF (SELECT COUNT(1) FROM customers WHERE customerid = #customerid) > 0
SET #FoundCustomer = 'Found'
ELSE
SET #FoundCustomer = 'Not Found'
END
SELECT #FoundCustomer
END

SQL: How to make table name in stored procedure dynamic

I am pretty new to SQL Server and hope someone here can help me with this (I'm using QL Server 2008).
The following is a small procedure that works as intended.
Now I would like to use the same procedure to update multiple tables as all these tables have exactly the same column names and column formatting, the only difference is the 2nd part of the table name for which I added XXX below.
Can someone tell me how this could be made dynamic and also provide me some explanations on this ?
I cannot provide much more here as I wasn't sure about how to approach this - other than probably declaring #sql nvarchar(max) and wrapping the whole query in SET #sql = N'...' before executing it.
My stored procedure:
CREATE PROCEDURE [dbo].[Cal_UpdateTeam]
#team nvarchar(100),
#teamID int,
#notes nvarchar(1000),
#log nvarchar(100),
#admin varchar(50)
AS
BEGIN
SET NOCOUNT ON;
BEGIN
IF NOT EXISTS
(
SELECT *
FROM Cal_XXX
WHERE teamID = #teamID
)
INSERT INTO Cal_XXX
(
team,
teamID,
notes,
log,
admin
)
SELECT #team,
#teamID,
#notes,
#log,
#admin
ELSE
UPDATE Cal_XXX
SET team = #team,
teamID = #teamID,
notes = #notes,
log = #log,
admin = #admin
WHERE teamID = #teamID
END
END
Many thanks for any tips and advise on this, Mike.
you should wrap your sql query in an nvarchar and then execute that query as in the below example :
declare #sql nvarchar(max)
declare #TableName nvarchar(max)
set #TableName = 'mytable'
set #sql = 'Select * from ' + #TableName
Exec sp_executesql #sql
in SP you can use Temporary Tables fro example:
CREATE PROCEDURE SELECT_TABLE
#REQUEST_ID INT
AS
BEGIN
/*************************************
** Temporary table **
*************************************/
CREATE TABLE #SOURCE (
ID INT
, ID_PARENT INT
, NAME VARCHAR(200)
, SORT INT
..
..
)
IF #REQUEST_ID = 'YES' BEGIN
INSERT INTO #SOURCE SELECT * FROM SOURCE_A
END
ELSE BEGIN
INSERT INTO #SOURCE SELECT * FROM SOURCE_B
END
SELECT * FROM #SOURCE
.....
END
GO
in SP you can encapsulate other SPs with different table names like parameter:
CREATE PROCEDURE SELECT_FROM_TABLE_A
AS
BEGIN
SELECT * FROM SOURCE_A
END
GO
CREATE PROCEDURE SELECT_FROM_TABLE_B
AS
BEGIN
SELECT * FROM SOURCE_B
END
GO
CREATE PROCEDURE SELECT_TABLE
#REQUEST_ID INT
AS
BEGIN
/**********************************************
** Subrequest select **
**********************************************/
IF #REQUEST_ID = 'YES' BEGIN
-- Request SP fro Source A
EXEC SELECT_FROM_TABLE_A
END
ELSE
BEGIN
-- Request SP fro Source B
EXEC SELECT_FROM_TABLE_B
END
END
GO

SQL Server : Dynamic Query in Stored Procedure in

I tried to write dynamic query in SQL Server. However I get warning like below,
The Selected stored procedure or function returns no columns
I have been trying to achieve this however it still does not run.
Where did I miss ?
ALTER PROCEDURE [dbo].[S_ProjeGetir1]
#ID int=0,
#AktifMi int,
#ProjeFirma int,
#Icinde int,
#AramaText Varchar(500),
#Arasinda1 Varchar(50),
#Arasinda2 Varchar(50)
AS
BEGIN
Create Table #TempTable
(Sonuc int
,ID int
,FirmaID int
,PrismProjeID int
,ProjeAdi nvarchar(150)
,RgID uniqueidentifier
,HaritaEnlem nvarchar(25)
,HaritaBoylam nvarchar(25)
,ProjeTeslimTarihi datetime
,HemenTeslimMi bit
,Adres nvarchar(250)
,AdresUlkeID int
,AdresILID int
,AdresILceID int
,AdresSemtID int
,KonutSayisi int
,LansmanTarihi datetime
,OfisSayisi int
,MagazaSayisi int
,BlokSayisi int
,YesilAlan int
,KrediyeUygunMu bit
,AktifMi bit
,UcBoyutVarMi bit
,UlkeAdi nvarchar(150)
,Sehir nvarchar(50)
,Ilce nvarchar(50)
,Semt nvarchar(50)
,FirmaAdi nvarchar(100)
,StokSonGuncellemeTarihi datetime)
Declare #SqlText varchar(8000),
#AktifPasif bit
Set #AktifPasif=Case When #AktifMi=0 Then 1 When #AktifMi=1 Then 0 End
SET NOCOUNT ON
BEGIN TRY
Set #SqlText=' SELECT 1 Sonuc ,[ID],[FirmaID] ,[PrismProjeID],[ProjeAdi] ,[RgID] ,[HaritaEnlem] ,[HaritaBoylam] ,[ProjeTeslimTarihi]
,[HemenTeslimMi],[Adres] ,[AdresUlkeID] ,[AdresILID] ,[AdresILceID] ,[AdresSemtID] ,[KonutSayisi]
,[LansmanTarihi],[OfisSayisi] ,[MagazaSayisi],[BlokSayisi],[YesilAlan] ,[KrediyeUygunMu],[AktifMi]
,[UcBoyutVarMi] ,[UlkeAdi] ,[Sehir] ,[Ilce] ,[Semt]
,[FirmaAdi] ,[StokSonGuncellemeTarihi]
FROM [dbo].[V_Proje] AS P WITH (NOLOCK)
WHERE 1=1 '
If #ID>0 Set --ID ye Göre İlgili Kayıdı almak için
#SqlText=#SqlText +' and ID=' +cast(#ID as Varchar(50))
Else
Begin
--Aktif ise veya Pasif ise
if #AktifMi=0 or #AktifMi=1
Begin
Set #SqlText=#SqlText +' and AktifMi='+cast(#AktifPasif as varchar(50))
End
--Bütün Alanları sorgulamak için
Set #SqlText=#SqlText +' and CASE WHEN '+cast(#ProjeFirma as varchar(50))+'=1 THEN Upper(ProjeAdi)
WHEN '+cast(#ProjeFirma as varchar(50))+'=0 THEN Upper(FirmaAdi)
WHEN '+cast(#ProjeFirma as varchar(50))+'=2 THEN Upper(HaritaEnlem)
WHEN '+cast(#ProjeFirma as varchar(50))+'=3 THEN Upper(HaritaBoylam)
WHEN '+cast(#ProjeFirma as varchar(50))+'=4 THEN Upper(Adres)'
If #Icinde=0--İçinde
Set #SqlText=#SqlText +' END Like ''%'+#AramaText+'%'' '
If #Icinde=1--İle Başlayan
Set #SqlText=#SqlText +' END Like '''+#AramaText+'%'' '
If #Icinde=2--Arasında
Set #SqlText=#SqlText +' END between '''+ #Arasinda1+''' and '''+#Arasinda2+''''
--select #SQLTEXT
End
exec('insert into #TempTable ' + #SqlText)
Select Sonuc, [ID],[FirmaID],[PrismProjeID],[ProjeAdi] ,[RgID] ,[HaritaEnlem],[HaritaBoylam],[ProjeTeslimTarihi],[HemenTeslimMi]
,[Adres] ,[AdresUlkeID] ,[AdresILID],[AdresILceID] ,[AdresSemtID],[KonutSayisi] ,[LansmanTarihi] ,[OfisSayisi]
,[MagazaSayisi],[BlokSayisi] ,[YesilAlan],[KrediyeUygunMu],[AktifMi] ,[UcBoyutVarMi],[UlkeAdi],[Sehir] ,[Ilce],[Semt]
,[FirmaAdi] ,[StokSonGuncellemeTarihi]
From #TempTable AS T WITH (NOLOCK)
END TRY
BEGIN CATCH
SELECT -1 AS Sonuc -- EXCEPTION
END CATCH
SET NOCOUNT OFF
END
Any help will be appreciated.
Thanks
I am not sure if what i am going to tell is going to work for EF, but i had a similar case in LINQ to SQL classes.
Backup the code of your Stored Procedure
Create a single SELECT statement with appropriate values, in your Stored Procedure like the following:
ALTER PROCEDURE [dbo].[S_ProjeGetir1]
#ID int=0,
#AktifMi int,
#ProjeFirma int,
#Icinde int,
#AramaText Varchar(500),
#Arasinda1 Varchar(50),
#Arasinda2 Varchar(50)
AS
BEGIN
Select CONVERT(VARCHAR(30),'') AS Sonuc, -- Make sure to convert to what your
0 AS [ID],
0 AS [FirmaID],
0 AS [PrismProjeID],
...
END
Import this Stored Procedure in EF
If all goes well, restore the backed up code in the Stored Procedure.

SQL Server: Return uniqueidentifier from stored procedure

Can I return UNIQUEIDENTIFIER from a stored procedure using the RETURN statement or is it only by using the OUTPUT statement?
i.e to return the PersonID UNIQUEIDENTIFIER:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT
AS
DECLARE #Count INT
DECLARE #JobFileGUID UNIQUEIDENTIFIER
-- Check if job exists?
SET #Count = (SELECT COUNT(Name) AS Name FROM Person WHERE Name=#Name)
IF #Count < 1
BEGIN
SET #PersonGUID = NEWID();
INSERT INTO Person
(PersonID, Name, [Desc])
VALUES (#PersonGUID, #Name, #Desc)
END
SELECT #PersonGUID = Person.PersonID
FROM Person
WHERE Name = #Name
RETURN #PersonGUID
GO
Thanks
In stored procedure - only using the OUTPUT statement. In function - return.
Use:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT,
#PersonGUID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET #PersonGUID = ...
END
How to call:
DECLARE
#name NVARCHAR(255),
#desc TEXT,
#personGUID UNIQUEIDENTIFIER
SET #name = 'Bob'
SET #desc = 'One handsome man.'
EXEC [Database].[schema].CreatePerson #name, #desc, #personGUID OUTPUT
From the documentation you can actually see that a return in a stored procedure is actually used as a response code, hence you get the exception when trying to return a uniqueidentifier.
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/return-data-from-a-stored-procedure?view=sql-server-ver16#return-data-using-a-return-code
How I solved it, is by just performing a SELECT after the insert of the generated unique identifier.
DECLARE #ReportId UNIQUEIDENTIFIER;
SET #ReportId = NEWID();
INSERT INTO [dbo].[Report]
([ReportId]
,[ReportName])
VALUES
(#ReportId
,#ReportName)
SELECT #ReportId as ReportIdInternal
You'll have to see how to perform that with multiple selects though.
CREATE TABLE [dbo].[tbl_Clients]( [ClientID] [uniqueidentifier] NULL, [ClientName] varchar NULL, [ClientEnabled] [bit] NULL ) ON [PRIMARY]
GO
CREATE PROCEDURE [dbo].[sp_ClientCreate] #in_ClientName varchar(250) = "New Client 123", #in_ClientEnabled bit, #out_ClientId uniqueidentifier OUTPUT AS
SET #out_ClientId = NEWID();
INSERT INTO tbl_Clients(ClientId, ClientName, ClientEnabled) VALUES( #out_ClientId, #in_ClientName, #in_ClientEnabled)
DECLARE #return_value int, #out_ClientId uniqueidentifier
EXEC #return_value = [dbo].[sp_ClientCreate] #in_ClientName = N'111', #in_ClientEnabled = 1, #out_ClientId = #out_ClientId OUTPUT
SELECT #out_ClientId as N'#out_ClientId'
SELECT 'Return Value' = #return_value
GO
Result:-59A6D7FE-8C9A-4ED3-8FC6-31A989CCC8DB

How to find data table column reference in stored procedures

I have changed a column name in a table in my SQL Server 2005 database. I also have a rather large collection of stored procedures that may or may not be referencing that column. Is there a way to find what stored procedures are referencing that column without actually going through each stored procedure and search for it manually? Is there a way to automatically find what stored procedures will now break or something? I do not have access to such SQL refactoring tools like RedGate's SQL Refactor.
Thanks!
Here is something that might help you. I have created two user stored procs that do something similar to what you are asking.
usp_depends2 - an extended version of sp_depends
usp_FindReferences - this one uses usp_depends2 to find all references for a column in a table (I think this is what you need)
/****** Object: StoredProcedure [dbo].[usp_depends2] Script Date: 11/18/2009 11:55:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[usp_depends2] --- 1996/08/09 16:51
#objname nvarchar(776) /* the object we want to check */
as
declare #objid int /* the id of the object we want */
declare #found_some bit /* flag for dependencies found */
declare #dbname sysname
/*
** Make sure the #objname is local to the current database.
*/
DECLARE #sp_depends_xref table (
reftype char(2)
, dep_name nvarchar(256)
, type char(16)
, updated char(7)
, selected char(8)
, [column] nvarchar(128))
select #dbname = parsename(#objname,3)
if #dbname is not null and #dbname <> db_name()
begin
raiserror(15250,-1,-1)
return (1)
end
/*
** See if #objname exists.
*/
select #objid = object_id(#objname)
if #objid is null
begin
select #dbname = db_name()
raiserror(15009,-1,-1,#objname,#dbname)
return (1)
end
/*
** Initialize #found_some to indicate that we haven't seen any dependencies.
*/
select #found_some = 0
set nocount on
/*
** Print out the particulars about the local dependencies.
*/
if exists (select *
from sysdepends
where id = #objid)
begin
raiserror(15459,-1,-1)
INSERT INTO #sp_depends_xref (
refType
, dep_name
, type
, updated
, selected
, [column])
select 'TO', 'name' = (s6.name+ '.' + o1.name),
type = substring(v2.name, 5, 16),
updated = substring(u4.name, 1, 7),
selected = substring(w5.name, 1, 8),
'column' = col_name(d3.depid, d3.depnumber)
from sysobjects o1
,master.dbo.spt_values v2
,sysdepends d3
,master.dbo.spt_values u4
,master.dbo.spt_values w5 --11667
,sysusers s6
where o1.id = d3.depid
and o1.xtype = substring(v2.name,1,2) collate database_default and v2.type = 'O9T'
and u4.type = 'B' and u4.number = d3.resultobj
and w5.type = 'B' and w5.number = d3.readobj|d3.selall
and d3.id = #objid
and o1.uid = s6.uid
and deptype < 2
select #found_some = 1
end
/*
** Now check for things that depend on the object.
*/
if exists (select *
from sysdepends
where depid = #objid)
begin
raiserror(15460,-1,-1)
INSERT INTO #sp_depends_xref (
RefType
, dep_name
, type)
select distinct 'BY', 'name' = (s.name + '.' + o.name),
type = substring(v.name, 5, 16)
from sysobjects o, master.dbo.spt_values v, sysdepends d,
sysusers s
where o.id = d.id
and o.xtype = substring(v.name,1,2) collate database_default and v.type = 'O9T'
and d.depid = #objid
and o.uid = s.uid
and deptype < 2
select #found_some = 1
end
/*
** Did we find anything in sysdepends?
*/
if #found_some = 0
raiserror(15461,-1,-1)
SELECT
reftype
, dep_name
, type
, updated
, selected
, [column]
FROM #sp_depends_xref
set nocount off
return (0) -- sp_depends
GO
/****** Object: StoredProcedure [dbo].[usp_FindReferences] Script Date: 11/18/2009 11:55:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_FindReferences]
-- Add the parameters for the stored procedure here
#tablename nvarchar(500) = 0,
#colname nvarchar(500) = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
create table #tempTableDependencies
(
reftype nvarchar(20),
dep_name nvarchar(500),
type nvarchar(500),
updated nvarchar(500),
selected nvarchar(500),
col nvarchar(500)
)
insert into #tempTableDependencies execute usp_depends2 #tablename
create table #tempDependencies
(
reftype nvarchar(20),
dep_name nvarchar(500),
type nvarchar(500),
updated nvarchar(500),
selected nvarchar(500),
col nvarchar(500)
)
declare #tempFilteredDependencies table
(
objectname nvarchar(500),
reftype nvarchar(20),
dep_name nvarchar(500),
type nvarchar(500),
updated nvarchar(500),
selected nvarchar(500),
col nvarchar(500)
)
DECLARE #loopcounter INT
select #loopcounter = COUNT(*) FROM #tempTableDependencies
DECLARE #dependencyname nvarchar(500)
WHILE #loopcounter > 0
BEGIN
SELECT TOP 1 #dependencyname = dep_name FROM #tempTableDependencies
print 'loop_counter = ' + CAST(#loopcounter as nvarchar(20))
print 'dependency = ' + #dependencyname
insert into #tempDependencies execute usp_depends2 #dependencyname
insert into #tempFilteredDependencies select #dependencyname as objectname, * from #tempDependencies where col = #colname and dep_name like '%' + #tablename
delete from #tempDependencies
delete from #tempTableDependencies where dep_name = #dependencyname
SET #loopcounter = #loopcounter - 1
END
select * from #tempFilteredDependencies
drop table #tempDependencies
drop table #tempTableDependencies
END
GO
The stock answer is "sp_depends", but in SQL 7.0 and 2000 it was not guaranteed to be accurate (that is, up to date). I don't know if they've addressed this in SQL 2005 or 2008, as I rolled my own work-around quite some time ago. This doesn't do exaclty what you want, but it can get you there sooner than otherwise
It's based on this query:
DECLARE #SearchText varchar(100)
SET #SearchText = 'ProductId'
SELECT
schema_name(ob.schema_id) SchemaName
,ob.name
,ob.type_desc
,len(mo.definition) CodeLength
,mo.definition
from sys.sql_modules mo
inner join .sys.objects ob
on ob.object_id = mo.object_id
where mo.definition like '%' + #SearchText + '%'
order by
case schema_name(ob.schema_id)
when 'dbo' then 'A'
else 'B' + str(ob.schema_id, 10)
end
,ob.type_desc
,ob.name
This will search through all the text-type database objects stored in sys.objects that have data/definitions in sys.modules. This covers stored procedures, functions, and views, and might also covers triggers and some constraints (I don't know one way or the other). It does not track synonyms, their definitions are stored in their own system table.
The results will return a list of all such objects that contain the specified string. It in no way tries to evaluate the context in which the string appears--if it's a table, column, variable, or comment, it's a hit and gets included. This means your mileage will vary depending on how unique the string your searching for is... but on the flip side, you can look for more than just columns with this.
Returned columns are:
SchemaName
Name (of object containing the
string)
type_desc (as from sys.objects)
CodeLength (how big is the chunk o'
code the string was found in)
definition (a copy of said chunk of
code. Hmm, I never use this, maybe I
should take it out?)
Here is what I found:
Nir method is best as it finds the real dependencies (not by the text of the stored procedure), though it will not work properly if you dont refresh sql module.
nip and Philip solutions are the same - find a string in the stored procedure code, it will not work properly if you have the same column name in several tables.
So I decided to use Nir's solution and add my script inside usp_FindReferences to refresh sql modules.
Here is my final script:
USE [Cetgroups3]
GO
/****** Object: StoredProcedure [dbo].[usp_depends2] Script Date: 03/16/2011 14:38:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[usp_depends2] --- 1996/08/09 16:51
#objname nvarchar(776) /* the object we want to check */
as
declare #objid int /* the id of the object we want */
declare #found_some bit /* flag for dependencies found */
declare #dbname sysname /* ** Make sure the #objname is local to the current database. */
DECLARE #sp_depends_xref table (
reftype char(2),
dep_name nvarchar(256),
type char(16),
updated char(7),
selected char(8),
[column] nvarchar(128))
select #dbname = parsename(#objname,3)
if #dbname is not null and #dbname <> db_name()
begin
raiserror(15250,-1,-1)
return (1)
end
/* ** See if #objname exists. */
select #objid = object_id(#objname)
if #objid is null
begin
select #dbname = db_name()
raiserror(15009,-1,-1,#objname,#dbname)
return (1)
end
/* ** Initialize #found_some to indicate that we haven't seen any dependencies. */
select #found_some = 0
set nocount on
/* ** Print out the particulars about the local dependencies. */
if exists (select * from sysdepends where id = #objid)
begin
raiserror(15459,-1,-1)
INSERT INTO #sp_depends_xref (refType, dep_name , type, updated, selected, [column])
select 'TO', 'name' = (s6.name+ '.' + o1.name), type = substring(v2.name, 5, 16),
updated = substring(u4.name, 1, 7), selected = substring(w5.name, 1,8),
'column' = col_name(d3.depid, d3.depnumber)
from sysobjects o1,
master.dbo.spt_values v2,
sysdepends d3,
master.dbo.spt_values u4,
master.dbo.spt_values w5, --11667
sysusers s6
where o1.id = d3.depid
and o1.xtype = substring(v2.name,1,2) collate database_default
and v2.type = 'O9T'
and u4.type = 'B'
and u4.number = d3.resultobj
and w5.type = 'B'
and w5.number = d3.readobj|d3.selall
and d3.id = #objid
and o1.uid = s6.uid
and deptype < 2
select #found_some = 1
end
/* ** Now check for things that depend on the object. */
if exists (select * from sysdepends where depid = #objid)
begin
raiserror(15460,-1,-1)
INSERT INTO #sp_depends_xref (RefType, dep_name, type)
select distinct 'BY', 'name' = (s.name + '.' + o.name), type = substring(v.name, 5, 16)
from sysobjects o,
master.dbo.spt_values v,
sysdepends d,
sysusers s
where o.id = d.id
and o.xtype = substring(v.name,1,2) collate database_default
and v.type = 'O9T'
and d.depid = #objid
and o.uid = s.uid
and deptype < 2
select #found_some = 1
end
/* ** Did we find anything in sysdepends? */
if #found_some = 0
raiserror(15461,-1,-1)
SELECT reftype, dep_name, type, updated, selected, [column]
FROM #sp_depends_xref
set nocount off
return (0) -- sp_depends
GO
/** Object: StoredProcedure [dbo].[usp_FindReferences] Script Date: 11/18/2009 11:55:05 **/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_FindReferences]
-- Add the parameters for the stored procedure here
#tablename nvarchar(500) = 0,
#colname nvarchar(500) = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements.
SET NOCOUNT ON;
-- Before starting - refresh sql module
declare #sql as nvarchar(max);
set #sql = '';
select #sql = #sql + N'begin try
exec sp_refreshsqlmodule #name = ''' + CAST(name as nvarchar(4000)) + N''';
end try
begin catch
print ''Failed to refresh ' + CAST(name as nvarchar(4000)) + N': '' + ERROR_MESSAGE();
IF XACT_STATE() = -1 ROLLBACK;
end catch;
'
from sys.sysobjects where type in ('P', 'V', 'TF', 'FN');-- order by name;
exec sp_executesql #sql;
-- Now we can proceed with fresh data
create table #tempTableDependencies (
reftype nvarchar(20),
dep_name nvarchar(500),
type nvarchar(500),
updated nvarchar(500),
selected nvarchar(500),
col nvarchar(500))
insert into #tempTableDependencies execute usp_depends2 #tablename
create table #tempDependencies (
reftype nvarchar(20),
dep_name nvarchar(500),
type nvarchar(500),
updated nvarchar(500),
selected nvarchar(500),
col nvarchar(500))
declare #tempFilteredDependencies table (
objectname nvarchar(500),
reftype nvarchar(20),
dep_name nvarchar(500),
type nvarchar(500),
updated nvarchar(500),
selected nvarchar(500),
col nvarchar(500))
DECLARE #loopcounter INT
select #loopcounter = COUNT(*) FROM #tempTableDependencies
DECLARE #dependencyname nvarchar(500)
WHILE #loopcounter > 0
BEGIN
SELECT TOP 1 #dependencyname = dep_name
FROM #tempTableDependencies
print 'loop_counter = ' + CAST(#loopcounter as nvarchar(20))
print 'dependency = ' + #dependencyname
insert into #tempDependencies execute usp_depends2 #dependencyname
insert into #tempFilteredDependencies
select #dependencyname as objectname, *
from #tempDependencies
where col = #colname
and dep_name like '%' + #tablename
delete from #tempDependencies
delete from #tempTableDependencies
where dep_name = #dependencyname
SET #loopcounter = #loopcounter - 1
END
select * from #tempFilteredDependencies order by objectname
drop table #tempDependencies
drop table #tempTableDependencies
END
GO
Something like that should do the trick
SELECT so.name
FROM sys.sysobjects so
JOIN sys.syscomments sc ON so.id = sc.id
WHERE sc.text LIKE '%ColumnName%'
AND so.type = 'P'