Find out the calling stored procedure in SQL Server - sql

Is it possible to find out who called a stored procedure?
For example, say I get an error in proc3. From within that proc I want to know if it was called by proc1 or proc2.

I would use an extra input parameter, to specify the source, if this is important for your logic.
This will also make it easier to port your database to another platform, since you don't depend on some obscure platform dependent function.

There is no nice automatic way to do this (alas). So it really depends on how much you are prepared to (re)write your procs in order to be able to do this.
If you have a logging mechanism, you might be able to read the log and work out who called you.
For example, if you implement logging by inserting to a table, for example:
CREATE TABLE Log
(timestamp dattime,
spid int,
procname varchar(255),
message varchar(255) )
... text of proc ...
INSERT INTO Log
SELECT get_date(), ##spid, #currentproc, 'doing something'
-- you have to define #currentproc in each proc
-- get name of caller
SELECT #caller = procname
FROM Log
WHERE spid = ##spid
AND timestamp = (SELECT max(timestamp)
FROM Log
WHERE timestamp < get_date()
AND procname != #currentproc )
This wouldn't work for recursive calls, but perhaps someone can fix that?

Do you need to know in proc3 at runtime which caused the error, or do you just need to know while debugging?
You can use SQL Server profiler if you only need to do it during debugging/monitoring.
Otherwise in 2005 I don't believe you have the ability to stack trace.
To work around it you could add and extra parameter to proc3, #CallingProc or something like that.
OR you could add try catch blocks to proc1 and proc2.
BEGIN TRY
EXEC Proc3
END TRY
BEGIN CATCH
SELECT 'Error Caught'
SELECT
ERROR_PROCEDURE()
END CATCH
Good reference here : http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1189087,00.html
and of course always SQL Server Books Online
SQL Server 2008 does have the ability to debug through procedures however.

You could have proc1 and proc2 pass their names into proc3 as a parameter.
For example:
CREATE PROCEDURE proc3
#Caller nvarchar(128) -- Name of calling proc.
AS
BEGIN
-- Produce error message that includes caller's name.
RAISERROR ('Caller was %s.', 16,10, #Caller);
END
GO
CREATE PROCEDURE proc1
AS
BEGIN
-- Get the name of this proc.
DECLARE #ProcName nvarchar(128);
SET #ProcName = OBJECT_NAME(##PROCID);
-- Pass it to proc3.
EXEC proc3 #ProcName
END
GO
CREATE PROCEDURE proc2
AS
BEGIN
-- Get the name of this proc.
DECLARE #ProcName nvarchar(128);
SET #ProcName = OBJECT_NAME(##PROCID);
-- Pass it to proc3.
EXEC proc3 #ProcName
END
GO

Related

Add Debug script into Stored Procedures

If you’re writing dynamic SQL, always add a Debug mode. It doesn’t have to be anything fancy at first, just something like:
IF #Debug = 1 BEGIN PRINT #MySQLInjectionGift END;
How can we use the above script in our Stored procedure
It can be used as a parameter to inject code.
DROP PROC IF EXISTS dbo.usp_myproc
GO
CREATE PROC dbo.usp_myproc (#Debug bit = 0)
AS
BEGIN
DECLARE #MySQLInjectionGift varchar(max) ='a=''HI THERE'','
DECLARE #SQL varchar(max) =
'
SELECT TOP 3'+IIF(#Debug=1,#MySQLInjectionGift,'')+'* FROM SYS.TABLES
'
EXEC (#SQL)
END
GO
EXEC usp_myproc
GO
EXEC usp_myproc #Debug = 1
You can do anything with it like create WHERE clauses on the fly, create columns that do calculations that are not part of the actual query but helpful in debugging. Typical injection include arbitrary SQL select statements that show progress from one SQL to another as when the stored procedure is large, the decision execution path may not be clear especially when there are lots of conditional statement. The debug mode can also run start-up code that can prepare the data or execute a unit test at the end of the query.

How do I limit a SQL stored procedure to be run by one person

I have a stored procedure that basically inserts from one table to another.
While this procedure is running, I don't want anyone else to be able to start it, however I don't want serialization, the other person to run the procedure after I am done with it.
What I want is for the other person trying to start it to get an error, while I am running the procedure.
I've tried with using sp_getapplock, however I can't manage to completely stop the person from running the procedure.
I also tried finding the procedure with sys.dm_exec_requests and blocking the procedure, while this does work, i think it's not optimal because on some servers I don't have the permissions to run sys.dm_exec_sql_text(sql_handle).
What is the best way for me to do this?
Cunning stunts:
ALTER PROC MyProc
AS
BEGIN TRY
IF OBJECT_ID('tembdb..##lock_proc_MyProc') IS NOT NULL
RAISERROR('Not now.', 16, 0)
ELSE
EXEC('CREATE TABLE ##lock_proc_MyProc (dummy int)')
...
EXEC('DROP TABLE ##lock_proc_MyProc')
END TRY
BEGIN CATCH
...
EXEC('DROP TABLE ##lock_proc_MyProc')
...
END CATCH
GO
Which can be extended by storing spid and watching for zombie ##.
Also you can just raise isolation level/granularity like TABLOCK, UPDLOCK:
ALTER PROC MyProc
AS
BEGIN TRAN
DECLARE #dummy INT
SELECT #dummy=1
FROM t (TABLOCKX, HOLDLOCK)
WHERE 1=0
...
COMMIT TRAN
this will have different effect - will wait, not fall.

Main Stored Procedure to Execute another Proc depending on Input and output in a CSV

I have two procedures which basically give an Table output. I have the third Procedure which basically calls these two procedures and gives the output in an csv file format.
Can anyone help me in building this the right way. Below is something I am trying to do:
Each of the two Procedures gives out an output with like around 100k rows, I want to capture that and want to give the output here from the Main procedure in a csv file.(Please let me know if you need more info)
Create PROC MAIN
#InputParam int
AS
Begin
Set NOCOUNT ON;
BEGIN TRY
IF #InputParam not in (1,2)
BEGIN
Print 'Error Message'
END
Else
begin
IF #InputParam=1
BEGIN
Exec StoredProc1
Print 'Stored Procedure StoredProc1 ended at '+Convert(Varchar(25),GETDATE(),21);
End
Else
Begin
Print 'StoredProc1 does not exist'
END
IF #InputParam=2
BEGIN
Exec StoredProc2
Print 'Stored Procedure StoredProc2 ended at '+Convert(Varchar(25),GETDATE(),21);
End
Else
BEGIN
Print 'StoredProc2 does not exist'
END
END -- This is END for ELSE loop
END TRY
Begin Catch
Print 'Input Validation Catch Block with # '+ Convert(Varchar(5),ERROR_NUMBER())+' Msg: '+ERROR_MESSAGE();
End Catch
END
What you may want to try is to declare a table vairable in your main stored procedure. This table needs to match the output from the sub procedures exactly. The syntax is:
DECLARE #Temp TABLE(
Filed1 INT,
Field2 VARCHAR(100),
etc
)
Then you can execute your sub stored procedure and insert into the table you defined, like this:
INSERT INTO #Temp
EXEC StoredProc1
And finally, select from the #Temp
SELECT * FROM #Temp
You will obviously need to fit your exact requirements into this, but it should assist I hope
You cannot output to a CSV directly from a Stored Procedure without some form of code, so that really depends what you are developing with (ie what will call the stored procedure). You could perhaps build a SQL Job to output to CSV.

SQL INSERT INTO calling Stored Procedure instead

I would like to do something like this in SQL
Insert Into storedproc2
SELECT column1, column2 from Tablename
My goal is to have each row of data in tablename processed using the storedproc2 stored procedure, which itself handles any insertion necessary in the logic flow.
Well as others said, you can't do that on a single statement. (that's just the way things work)
If what you wan't is to call a proc with the results you can first select and then call the proc using a cursor.
The cursor would perform a row by row code and you would be able to call the proc passing the correct values. But beware cursors are slow use Flags like FAST_FORWARD.
The other way would be to change your proc to accept a whole table, as a table valued parameter, if that is possiblel, that would perform really better.
Hope this helps.
DECLARE CallingProcCursor CURSOR
FAST_FORWARD
FOR
SELECT database_id,name from sys.databases
DECLARE #database_id int, #name sysname
OPEN CallingProcCursor
FETCH NEXT FROM CallingProcCursor INTO #database_id, #name
WHILE (##fetch_status <> -1)
BEGIN
IF (##fetch_status <> -2)
BEGIN
EXEC PROCX #database_id, #name
END
FETCH NEXT FROM CallingProcCursor INTO #database_id, #name
END
CLOSE CallingProcCursor
DEALLOCATE CallingProcCursor
GO
You can't insert into a stored procedure. You can only insert into a table (and in some cases a view, depending on the DB platform and whether the view is updateable.)
You can use a stored procedure to insert data as shown here: http://www.codeproject.com/KB/cs/tariqaziz.aspx
This is NOT meant to be insulting, but rather helpful...
It sounds like you need to go read up on stored procedures, since your question shows that you don't get the basics.
http://databases.about.com/od/sqlserver/a/storedprocedure.htm
As David said, you can't do this the way you want.
What you CAN do is feed the stored proc a table as a parameter, and have it perform it's logic on each row in that table. It will involve some Dynamic SQL but it is doable.
you can put insert statement inside stored proc and pass the values as parameters e.g.
following is just an example, on each row you can call your stored proc and it should be fine
CREATE PROC BDD_AddMessageLogItem(
#BusinessDevelopmentItemId INT,
#MessageLog NVARCHAR(MAX),
#PostedBy SMALLINT,
#PostedOfficeId TINYINT,
#PostedDepartmentId TINYINT,
#PostedMessageLogType TINYINT)
AS
BEGIN
DECLARE #BusinessDevelopmentMessageLogId SMALLINT
INSERT INTO dbo.BusinessDevelopmentItemMessageLogs
( BusinessDevelopmentItemId ,
MessageLog ,
DatePosted,
PostedBy,
PostedOfficeId,
PostedDepartmentId,
PostedMessageLogType,
BusinessDevelopmentMessageLogId
)
VALUES ( #BusinessDevelopmentItemId , -- BusinessDevelopmentItemId - int
#MessageLog , -- Message - nvarchar(100)
GETDATE(),
#PostedBy,
#PostedOfficeId,
#PostedDepartmentId,
#PostedMessageLogType,
#BusinessDevelopmentMessageLogId
)
END
You can't pass data sets to stored procedures, only parameters. You could:
Pass the table name to the stored procedure and then construct the select.
Pass the whole query as a parameter.
And then execute it with sp_executesql. If you use this method you should read The Curse and Blessings of Dynamic SQL.

How to Suppress the SELECT Output of a Stored Procedure called from another Stored Procedure in SQL Server?

I'm not talking about doing a "SET NOCOUNT OFF". But I have a stored procedure which I use to insert some data into some tables. This procedure creates a xml response string, well let me give you an example:
CREATE PROCEDURE [dbo].[insertSomeData] (#myParam int) AS
DECLARE #reply varchar(2048)
... Do a bunch of inserts/updates...
SET #reply = '<xml><big /><outputs /></xml>'
SELECT #reply
GO
So I put together a script which uses this SP a bunch of times, and the xml "output" is getting to be too much (it's crashed my box once already).
Is there a way to suppress or redirect the output generated from this stored procedure? I don't think that modifying this stored procedure is an option.
thanks.
I guess i should clarify. This SP above is being called by a T-SQL Update script that i wrote, to be run through enterprise studio manager, etc.
And it's not the most elegant SQL i've ever written either (some psuedo-sql):
WHILE unprocessedRecordsLeft
BEGIN
SELECT top 1 record from updateTable where Processed = 0
EXEC insertSomeData #param = record_From_UpdateTable
END
So lets say the UpdateTable has some 50k records in it. That SP gets called 50k times, writing 50k xml strings to the output window. It didn't bring the sql server to a stop, just my client app (sql server management studio).
The answer you're looking for is found in a similar SO question by Josh Burke:
-- Assume this table matches the output of your procedure
DECLARE #tmpNewValue TABLE ([Id] int, [Name] varchar(50))
INSERT INTO #tmpNewValue
EXEC [ProcedureB]
-- SELECT [Id], [Name] FROM #tmpNewValue
I think I found a solution.
So what i can do now in my SQL script is something like this (sql-psuedo code):
create table #tmp(xmlReply varchar(2048))
while not_done
begin
select top 1 record from updateTable where processed = 0
insert into #tmp exec insertSomeData #param=record
end
drop table #tmp
Now if there was a even more efficient way to do this. Does SQL Server have something similar to /dev/null? A null table or something?
Answering the question, "How do I suppress stored procedure output?" really depends on what you are trying to accomplish. So I want to contribute what I encountered:
I needed to supress the stored procedure (USP) output because I just wanted the row count (##ROWCOUNT) from the output. What I did, and this may not work for everyone, is since my query was already going to be dynamic sql I added a parameter called #silentExecution to the USP in question. This is a bit parameter which I defaulted to zero (0).
Next if #silentExecution was set to one (1) I would insert the table contents into a temporary table, which is what would supress the output and then execute ##ROWCOUNT with no problem.
USP Example:
CREATE PROCEDURE usp_SilentExecutionProc
#silentExecution bit = 0
AS
BEGIN
SET NOCOUNT ON;
DECLARE #strSQL VARCHAR(MAX);
SET #strSQL = '';
SET #strSQL = 'SELECT TOP 10 * ';
IF #silentExecution = 1
SET #strSQL = #strSQL + 'INTO #tmpDevNull ';
SET #strSQL = #strSQL +
'FROM dbo.SomeTable ';
EXEC(#strSQL);
END
GO
Then you can execute the whole thing like so:
EXEC dbo.usp_SilentExecutionProc #silentExecution = 1;
SELECT ##ROWCOUNT;
The purpose behind doing it like this is if you need the USP to be able to return a result set in other uses or cases, but still utilize it for just the rows.
Just wanted to share my solution.
I have recently come across with a similar issue while writing a migration script and since the issue was resolved in a different way, I want to record it.
I have nearly killed my SSMS Client by running a simple while loop for 3000 times and calling a procedure.
DECLARE #counter INT
SET #counter = 10
WHILE #counter > 0
BEGIN
-- call a procedure which returns some resultset
SELECT #counter-- (simulating the effect of stored proc returning some resultset)
SET #counter = #counter - 1
END
The script result was executed using SSMS and default option on query window is set to show “Results to Grid”[Ctrl+d shortcut].
Easy Solution:
Try setting the results to file to avoid the grid to be built and painted on the SSMS client. [CTRL+SHIFT+F keyboard shortcut to set the query results to file].
This issue is related to : stackoverflow query
Man, this is seriously a case of a computer doing what you told it to do instead of what you wanted it to do.
If you don't want it to return results, then don't ask it to return results. Refactor that stored procedure into two:
CREATE PROCEDURE [dbo].[insertSomeData] (#myParam int) AS
BEGIN
DECLARE #reply varchar(2048)
--... Do a bunch of inserts/updates...
EXEC SelectOutput
END
GO
CREATE PROCEDURE SelectOutput AS
BEGIN
SET #reply = '<xml><big /><outputs /></xml>'
SELECT #reply
END
From which client are you calling the stored procedure? Say it was from C#, and you're calling it like:
var com = myConnection.CreateCommand();
com.CommandText = "exec insertSomeData 1";
var read = com.ExecuteReader();
This will not yet retrieve the result from the server; you have to call Read() for that:
read.Read();
var myBigString = read[0].ToString();
So if you don't call Read, the XML won't leave the Sql Server. You can even call the procedure with ExecuteNonQuery:
var com = myConnection.CreateCommand();
com.CommandText = "exec insertSomeData 1";
com.ExecuteNonQuery();
Here the client won't even ask for the result of the select.
You could create a SQL CLR stored procedure that execs this. Should be pretty easy.
I don't know if SQL Server has an option to suppress output (I don't think it does), but the SQL Query Analyzer has an option (under results tab) to "Discard Results".
Are you running this through isql?
You said your server is crashing. What is crashing the application that consumes the output of this SQL or SQL Server itself (assuming SQL Server).
If you are using .Net Framework application to call the stored procedure then take a look at SQLCommand.ExecuteNonQuery. This just executes stored procedure with no results returned. If problem is at SQL Server level then you are going to have to do something different (i.e. change the stored procedure).
You can include in the SP a parameter to indicate if you want it to do the select or not, but of course, you need to have access and reprogram the SP.
CREATE PROCEDURE [dbo].[insertSomeData] (#myParam int, #doSelect bit=1) AS
DECLARE #reply varchar(2048)
... Do a bunch of inserts/updates...
SET #reply = '<xml><big /><outputs /></xml>'
if #doSelect = 1
SELECT #reply
GO
ever tried SET NOCOUNT ON; as an option?