Issue:
I'm getting this error on Microsoft SQL Server 2008:
Msg 8164, Level 16, State 1, Procedure sp_MSload_tmp_replication_status, Line 80
An INSERT EXEC statement cannot be nested.
Background:
I'm trying to programmatically monitor replication status in Microsoft SQL Server. I'm using INSERT EXEC statement on sp_replmonitorhelppublisher to get the status, questions that will follow are not restricted to this proc, but I'm mentioning it because the proc is built-in, so I cannot rewrite it to get the data "the way it should be done". My (simplified) code to get the data is:
declare #t table (
publisher nvarchar(max) null,
distribution_db nvarchar(max) null,
status nvarchar(max) null,
warning nvarchar(max) null,
publicationcount nvarchar(max) null,
returnstamp nvarchar(max) null
)
insert into #t exec sp_replmonitorhelppublisher 'MY_PUBLISHER'
Questions:
I understand the MS SQL Server restriction that is causing the error, I guess that there is some INSERT EXEC statement somewhere inside the built-in proc. What I don't understand is:
Why it sometimes works without the error (I've seen it a couple of times run successfully)?
Why a workaround of running the same EXEC statement (not as part of INSERT EXEC) before the actual INSERT EXEC works without errors? I.e. this code works OK:
declare #t table (
publisher nvarchar(max) null,
distribution_db nvarchar(max) null,
status nvarchar(max) null,
warning nvarchar(max) null,
publicationcount nvarchar(max) null,
returnstamp nvarchar(max) null
)
exec sp_replmonitorhelppublisher 'MY_PUBLISHER' -- extra call before main call
insert into #t exec sp_replmonitorhelppublisher 'MY_PUBLISHER'
Is this workaround guaranteed to run without the error? And why?
Or is there some form of caching involved, that happens to be working for me, but is not guaranteed to work on every call?
Is there any better way of programmatically monitoring replication?
I was working on the same issue - programatically monitoring replication status. I've found out that executing sp_replmonitor* stored procedures also updates the table dbo.MSReplication_monitordata. This table holds the current status information of replication.
So, my solution was to execute the sp_replmonitorhelppublisher and then read the values from the dbo.MSReplication_monitordata.
For example: Starting the publication and I waiting for it to finish (in a SQL Server Agent job) is done by this:
USE [DB]
DECLARE #StartDateTime datetime = GETDATE()
EXEC sp_startpublication_snapshot #publication='publ_DB'
USE [distribution]
DECLARE #Status int = 1
WHILE #status NOT IN (2, 6)
BEGIN
WAITFOR DELAY '00:00:05'
EXEC sp_replmonitorhelppublisher
SELECT #Status = status FROM dbo.MSReplication_monitordata WHERE publication='publ_DB' AND agent_type=1 AND time_stamp>#StartDateTime
END
Hope this helps!
Related
I'm having a problem and I don't know how to solve it, I have searched the web and found good advice but I can't work it out.
This is the problem: I have a SQL Server instance running on my PC, and I linked one of the main servers SRVOLD\SQLDESA to it. I want to execute main server's stored procedures from my PC's SQL Server instance and insert the results into a new table. I found the perfect way to do it using the following:
SELECT *
INTO Bank
FROM OPENQUERY([SRVOLD\SQLDESA],
'EXEC Bank_Database.Bank.usp_GetTDcodes 1, 5')
GO
There is important information about this server, it's SQL Server version is 2008. Keep this in mind for later.
Ok so I managed to executed this Stored Procedure but I found out something, turns out that inside this Stored Procedure there's an execution of another stored procedure, check this out:
1st stored procedure:
CREATE PROCEDURE Bank.usp_GetTDcodes
(#code TINYINT = NULL, #qty TINYINT = NULL)
WITH ENCRYPTION
AS
DECLARE ##msg VARCHAR(100)
DECLARE ##OK INT
DECLARE ##today CHAR(30)
SELECT ##today = CONVERT(VARCHAR(30), GETDATE(), 112) + ' ' +
CONVERT(VARCHAR(30), GETDATE(), 8)
SELECT bnk_code, bnk_descr
FROM CODBNK
WHERE bnk_code < 50
EXECUTE ##OK = Bank.usp_WriteEvent #qty, #code, ##today, 500
IF ##OK <> 0
RETURN ##OK
RETURN 0
GO
Now let's look inside the 2nd stored procedure:
CREATE PROCEDURE Bank.usp_WriteEvent
(#code TINYINT = NULL,
#qty TINYINT = NULL,
#date DATETIME = NULL,
#number SMALLINT = NULL,
#ideve INT = 0 OUTPUT)
WITH ENCRYPTION
AS
DECLARE ##sdate VARCHAR(30)
DECLARE ##ret SMALLINT
INSERT INTO Event (eve_code, eve_qty, eve_date, eve_number)
VALUES (#code, #qty, #date, #number)
SET ##ret = ##error
IF ##ret = 0
BEGIN
SELECT #ideve = ##IDENTITY
SELECT ##sdate = CONVERT(VARCHAR(30), #date, 112) + ' ' +
VARCHAR(30), #date, 8)
END
ELSE
RETURN ##ret
GO
When I executed the 1st stored procedure, I was able to insert it's result into a new table, but I was hoping to find a new row inserted in the table Event, because that is the expected result when executing 2nd stored procedure.
So I started to search online and managed to achieve this by doing the following:
SELECT *
INTO Bank
FROM OPENQUERY([SRVTEST\SQLDESA],
'SET FMTONLY OFF;SET NOCOUNT ON;EXEC Bank_Database.Bank.usp_GetTDcodes 1, 5')
GO
So, the SET FMTONLY OFF;SET NOCOUNT ON worked and I was happy. But something happened...
I needed to execute the same stored procedure, but this time adding a new linked server SRVNEW\SQLDESA. This server's version is 2012, so the new solution didn't work. I kept trying and trying different ways, there's just one way to make it work and is the following:
EXEC [SRVNEW\SQLDESA].[Bank_Database].Bank.usp_GetTDcodes 1,5
But it doesn't work for me because I need the 1st stored procedure result into a new table. And I don't know its schema that's why SELECT INTO works best for me.
I don't know what else I can do, maybe is the OPENQUERY that doesn't work? Do I need to change something else?
PD: I also tried using OPENROWSET didn't work either.
Thanks in advance, and have a nice day!
Peace!
Some references: http://www.sommarskog.se/share_data.html#OPENQUERY
I'm currently trying to write a default procedure template for reporting from a T-SQL Datawarehouse.
The idea is to wrap each query in a procedure, so that permissions and logging can be managed easily.
Since this will be done by the DBAs, I would like to have this solution work by only pasting some standard code before and after the main query. I'd prefer if the DBA didn't have to modify any part of the logging-code.
I've solved this for most parts, however, I need to log which parameters the user has submitted to the procedure.
The obvious solution would be hardcode the parameters into the logging. However, the procedures can have a varying amount of parameters, and I'd therefore like a catch-all solution.
My understanding is that there is no easy way iterating through all parameters.
I can however access the parameter-names from the table sys.parameters.
The closest to a solution I've come, is this minimal example:
CREATE TABLE #loggingTable (
[ProcedureID] INT
, [paramName] NVARCHAR(128)
, [paramValue] NVARCHAR(128)
)
;
go
CREATE PROCEDURE dbo.[ThisIsMyTestProc] (
#param1 TINYINT = NULL
, #Param2 NVARCHAR(64) = null
)
AS
BEGIN
-- Do some logging here
DECLARE #query NVARCHAR(128)
DECLARE #paramName NVARCHAR(128)
DECLARE #paramValue nvarchar(128)
DECLARE db_cursor CURSOR FOR
SELECT [name] FROM [sys].[parameters] WHERE object_id = ##PROCID
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #paramName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #query = 'SELECT #paramValue = cast(' + #paramName + ' as nvarchar(128))';
SELECT #query;
-- Following line doesn't work due to scope out of bounds, and is prone to SQL-Injections.
--EXEC SP_EXECUTESQL #query; -- Uncomment for error
insert into #loggingTable(ProcedureID, paramName, paramValue)
values(##PROCID, #paramName, #paramValue)
FETCH NEXT FROM db_cursor INTO #paramName
END
CLOSE db_cursor
DEALLOCATE db_cursor
-- Run the main query here (Dummy statement)
SELECT #param1 AS [column1], #Param2 AS [column2]
-- Do more logging after statement has run
END
GO
-- test
EXEC dbo.[ThisIsMyTestProc] 1, 'val 2';
select * from #loggingTable;
-- Cleanup
DROP PROCEDURE dbo.[ThisIsMyTestProc];
DROP table #loggingTable;
However, this does have to major drawbacks.
It doesn't work due to variable scopes
It is prone to SQL-Injections, which is unacceptable
Is there any way to solve this issue?
The values of the parameters are not availiable in a generic approach. You can either create some code generator, which will use sys.parameters to create a chunk of code you'd have to copy into each of your SPs, or you might read this or this about tracing and XEvents. The SQL-Server-Profiler works this way to show you statements together with the parameter values...
If you don't want to get into tracing or XEvents you might try something along this:
--Create a dummy proc
CREATE PROCEDURE dbo.[ThisIsMyTestProc] (
#param1 TINYINT = NULL
, #Param2 NVARCHAR(64) = null
)
AS
BEGIN
SELECT ##PROCID;
END
GO
--call it to see the value of ##PROCID
EXEC dbo.ThisIsMyTestProc; --See the proc-id
GO
--Now this is the magic part. It will create a command, which you can copy and paste into your SP:
SELECT CONCAT('INSERT INTO YourLoggingTable(LogType,ObjectName,ObjectId,Parameters) SELECT ''ProcedureCall'', ''',o.[name],''',',o.object_id,','
,'(SELECT'
,STUFF((
SELECT CONCAT(',''',p.[name],''' AS [parameter/#name],',p.[name],' AS [parameter/#value],''''')
FROM sys.parameters p
WHERE p.object_id=o.object_id
FOR XML PATH('')
),1,1,'')
,' FOR XML PATH(''''),ROOT(''parameters''),TYPE)'
)
FROM [sys].[objects] o
WHERE o.object_id = 525244926; --<-- Use the proc-id here
--Now we can copy the string into our procedure
--I out-commented the INSERT part, the SELECT is enough to show the effect
ALTER PROCEDURE dbo.[ThisIsMyTestProc] (
#param1 TINYINT = NULL
, #Param2 NVARCHAR(64) = null
)
AS
BEGIN
--The generated code comes in one single line
--INSERT INTO YourLoggingTable(LogType,ObjectName,ObjectId,Parameters)
SELECT 'ProcedureCall'
,'ThisIsMyTestProc'
,525244926
,(SELECT'#param1' AS [parameter/#name],#param1 AS [parameter/#value],''
,'#Param2' AS [parameter/#name],#Param2 AS [parameter/#value],''
FOR XML PATH(''),ROOT('parameters'),TYPE)
END
GO
Hint: We need the empty element (,'') at the end of each line to allow multiple elements with the same name.
--Now we can call the SP with some param values
EXEC dbo.ThisIsMyTestProc 1,'hello';
GO
As a result, your Log-Table will get an entry like this
ProcedureCall ThisIsMyTestProc 525244926 <parameters>
<parameter name="#param1" value="1" />
<parameter name="#Param2" value="hello" />
</parameters>
Just add typical logging data like UserID, DateTime, whatever you need...
Scope is the killer issue for this approach. I don't think there's a way to reference the values of parameters by anything but their variable names. If there was a way to retrieve variable values from a collection or by declared ordinal position, it could work on the fly.
I understand wanting to keep the overhead for the DBAs low and eliminating opportunities for error, but I think the best solution is to generate the required code and supply it to the DBAs or give them a tool that generates the needed blocks of code. That's about as lightweight as we can make it for the DBA, but I think it has the added benefit of eliminating processing load in the procedure by turning it into a static statement with some conditional checking for validity and concatenation work. Cursors and looping things should be avoided as much as possible.
Write a SQL script that generates your pre- and post- query blocks. Generate them in mass with a comment at the top of each set of blocks with the stored procedure name and hand it to the DBAs to copy/paste into the respective procs. Alternatively, give them the script and let them run it as needed to generate the pre- and post- blocks themselves.
I would include some checks in the generated script to help make sure it works during execution. This will detect mismatches in the generated code due to subsequent modifications to the procedure itself. We could go the extra mile and include the names of the parameters when the code is generated and verify them against sys.parameters to make sure the parameter names hard-coded into the generated code haven't changed since code generation.
-- Log execution details pre-execution
IF object_name(##PROCID) = 'ThisIsMyTestProc' AND (SELECT COUNT(*) FROM [sys].[parameters] WHERE object_id = ##PROCID) = 2
BEGIN
EXEC LogProcPreExecution #Params = CONCAT('parm1: ', #param1, ' parm2: ', #Param2), #ProcName = 'ThisIsMyTestProc', #ExecutionTime = getdate() #ExecutionUser = system_user
END
ELSE
BEGIN
--Do error logging for proc name and parameter mismatch
END
--Log procedure would look like this
CREATE PROCEDURE
LogProcPreExecution
#Parameters varchar(max),
#ProcName nvarchar(128),
#ExecutionTime datetime,
#ExecutionUser nvarchar(50)
AS
BEGIN
--Do the logging
END
CREATE PROC add_person
(
#id tinyint,
#name nvarchar(max),
#surname nvarchar(max),
#salary int,
#job nvarchar(max)
)
AS
BEGIN
INSERT INTO information
VALUES(#id,#name,#surname,#salary,#job)
END
I want to write this code as a function. But the concept of "return" confuses me. That's why I couldn't.
I tried to write the code above as a function. This code came out.
CREATE FUNCTION add_person
(
#id tinyint,
#name nvarchar(max),
#surname nvarchar(max),
#salary int,
#job nvarchar(max)
)
RETURNS TABLE
AS
BEGIN
RETURN INSERT INTO information -- not work
VALUES(#id,#name,#surname,#salary,#job)
END
If you want to return the newly created table, you can use the stored procedure to do that. If you're using SQL Server, the code would be:
BEGIN
INSERT INTO information -- not work
VALUES(#id,#name,#surname,#salary,#job);
SELECT * FROM information WHERE id = ##identity; -- this is the primary key just created.
END
Functions are much more limited in their functionality than are stored procedures.
Although insert is allowed, it is only allowed in local variables. As the documentation says:
INSERT, UPDATE, and DELETE statements modifying local table variables.
On the other hand, a stored procedure can return a value. Normally, this is a status code, where 0 means everything succeeded, and any other value means that the process failed.
Consider the following stored procedure..
CREATE PROCEDURE SlowCleanUp (#MaxDate DATETIME)
AS
BEGIN
PRINT 'Deleting old data Part 1/3...'
DELETE FROM HugeTable1 where SaveDate < #MaxDate
PRINT 'Deleting old data Part 2/3...'
DELETE FROM HugeTable2 where SaveDate < #MaxDate
PRINT 'Deleting old data Part 3/3...'
DELETE FROM HugeTable3 where SaveDate < #MaxDate
PRINT 'Deleting old data COMPLETED.'
END
Let's say that each delete statement take a long time to delete, but I like to see the progress of this stored procedure when I'm running it in SQL Management Studio. In other words, I like to see the the output of the PRINT statements to see where I'm at any given time. However, it seems that I can only see the PRINT outputs at the end of the ENTIRE run. Is there a way to make it so that I can see the PRINT outputs at real time? If not, is there any other way I can see the progress of a running stored procedure?
If you use RAISERROR with a severity of 10 or less, and use the NOWAIT option, it will send an informational message to the client immediately:
RAISERROR ('Deleting old data Part 1/3' , 0, 1) WITH NOWAIT
Yes you should be able to get the message to print immediately if you use RAISERROR:
RAISERROR('Hello',10,1) WITH NOWAIT
I have found a great NON-INTRUSIVE way to see the progress of along running stored procedure. Using code I found on Stackoverflow of SP_WHO2, you can see the first column has the current code actually being run from the PROC. Each time you re-run this SP_Who2 process, it will display the code running at the time.This will let u know how far along your proc is at anytime. Here is the sp_who2 code which I modified to make it easier to track progress:
Declare #loginame sysname = null
DECLARE #whotbl TABLE
(
SPID INT NULL
,Status VARCHAR(50) NULL
,Login SYSNAME NULL
,HostName SYSNAME NULL
,BlkBy VARCHAR(5) NULL
,DBName SYSNAME NULL
,Command VARCHAR(1000) NULL
,CPUTime INT NULL
,DiskIO INT NULL
,LastBatch VARCHAR(50) NULL
,ProgramName VARCHAR(200) NULL
,SPID2 INT NULL
,RequestID INT NULL
)
INSERT INTO #whotbl
EXEC sp_who2 #loginame = #loginame
SELECT CommandText = sql.text ,
W.*
,ExecutionPlan = pln.query_plan
,ObjectName = so.name
,der.percent_complete
,der.estimated_completion_time
--,CommandType =der.command
FROM #whotbl W
LEFT JOIN sys.dm_exec_requests der
ON der.session_id = w.SPID
OUTER APPLY SYS.dm_exec_sql_text (der.sql_handle) Sql
OUTER APPLY sys.dm_exec_query_plan (der.plan_handle) pln
LEFT JOIN sys.objects so
I wish I remember who I got this original code from, but it has been VERY helpful. It also identifies the SPID if I need to kill a process.
i have an SQL statement wherein i am trying to update the table on the client's machine.
the sql statement is as follows:
BEGIN TRANSACTION
DECLARE #CreatedBy INT
SELECT #CreatedBy = [User_Id]
FROM Users
WHERE UserName = 'Administrator'
--////////////////////////////////////////////////////////////////////
--////////////////////////////////////////////////////////////////////
PRINT #CreatedBy --(Works fine here and shows me the output)
PRINT N'Rebuilding [dbo].[Some_Master]'
ALTER TABLE [dbo].[Some_Master]
ADD [CreatedBy] [BIGINT] NULL,
[Reason] [VARCHAR](200) NULL
GO
PRINT #CreatedBy --(does not work here and throws me an error)
PRINT N'Updating data in [Some_Master] table'
UPDATE Some_Master
SET CreatedBy = #CreatedBy
COMMIT TRANSACTION
but i am getting the following error:
Must declare the scalar variable "#CreatedBy".
Now i have observed if i write the Print statement above the alter command it works fine and shows me its value, but if i try to print the value after the Alter command it throws me the error i specified above.
I dont know why ?? please help!
Thank you
It's because of the GO, which signals the end of a batch of commands. So after the GO, it is a separate batch whereby the variable #CreatedBy is no longer in scope.
Try removing the GO statements.
I think you need to remove the GO statement.
Remove the "GO" statement.