Select statement after insert hangs? - tsql

In my stored procedure I am trying to insert records in to a temporary table
In my stored procedure I am trying to insert records in to a temporary table
--Temporary table
create table #CR_TMP
(
ct_co_id int NULL
, ct_nbr int NULL
, ctrct_srvc_type char(4) NULL
, start_date datetime NULL
, end_date datetime NULL
)
print 'Before insert'
Insert into #CR_TMP
select distinct col1,col2,......
from tableName
where conditions
print 'After insert'
select '#CR_TMP' as #CR_TMP, * from #CR_TMP
print 'here 1'
I ran the select query and it gives about 583 rows.
But when I execute the above procedure. I think it's getting stuck on the insert procedure.
I do get the result 'After insert' but I don't get the results for print 'here 1'.
I had this procedure executing for 2 hours and it was stuck at the same place. Any pointers here?
I ran the select query and it gives about 583 rows.
But when I execute the above procedure. I think it's getting stuck on the insert procedure.
I do get the result 'After insert' but I don't get the results for print 'here 1'.
I had this procedure executing for 2 hours and it was stuck at the same place. Any pointers here?

The procedure looks good except for this part:
print 'After insert'
select '#CR_TMP' as #CR_TMP, *
from #CR_TMP
print 'here 1'
Try changing this to:
print 'After insert'
select '#CR_TMP' as [#CR_TMP], *
from #CR_TMP
print 'here 1'
Or even remove the first part of the select
print 'After insert'
select *
from #CR_TMP
print 'here 1'
Edit:
After a discussion in chat, it was determined that the initial portion of the stored procedure that sanika thought was the issue actually was working. So I advised that they start working query by query back into a test to determine where the actual problem is. At that point, it will be easier to debug a 30 page stored procedure.

Related

SQL query returns necessary data, but the procedure doesn't

I need to create a procedure that returns the list of entries from two tables. Here's the code for the procedure:
create or replace PROCEDURE goods_to_transfer
IS
begin
for rec in (select sales.good_id, sales.good_count, goods.priority
FROM goods,sales
where sales.good_id=goods.id and sales.delivered='YES');
loop
dbms_output.put_line( 'GOOD ID' || rec.good_id);
dbms_output.put_line( 'GOOD COUNT' || rec.good_count);
dbms_output.put_line( 'PRIORITY' || rec.good_priority);
end loop;
end goods_to_transfer;
The execution ends up with the following mistakes:
ORA-01403: no data found
ORA-06512: in "C##XSENIA.GOODS_TO_TRANSFER", line 7
ORA-06512: in line 2
The same query returns all the necessary data:
select sales.good_id, sales.good_count, goods.priority FROM goods,sales
where sales.good_id=goods.id and sales.delivered='YES'
I wonder if anyone could possibly tell me, what do I do wrong.
Thank you!
try to remove the ; at the end of the request
for rec in (select sales.good_id, sales.good_count, goods.priority
FROM goods,sales
where sales.good_id=goods.id and sales.delivered='YES')

insert into select - stored procedure affects 0 rows

I am using SQL Server 2014. I created a stored procedure to update a table, but when i run this it affects 0 rows. i'm expecting to see 501 rows affected, as the actual insert statement when run alone returns that.The table beingupdated is pre-populated.
I also tried pre-populating the table with 500 records to see if the last 1 row was pulled by the stored procedure, but it still affects 0 rows.
Create PROCEDURE UPDATE_STAGING
(#StatementType NVARCHAR(20) = '')
AS
BEGIN
IF #StatementType = 'Insertnew'
BEGIN
INSERT INTO owner.dbo.MVR_Staging
(
policy_number,
quote_number,
request_id,
CreateTs,
mvr_response_raw_data
)
select
p.pol_num,
A.pol_number,
R.Request_ID,
R.CreateTS,
R._raw_data
from TABLE1 A with (NOLOCK)
left join TABLE2 R with (NOLOCK)
on R.Request_id = isnull(A.CACHE_REQUEST_ID, A.Request_id)
inner join TABLE3 P
on p.quote_policy_num = a.policy_number
where
A.[SOURCE] = 'MVR'
and A.CREATED_ON >= '2020-01-01'
END
IF #StatementType = 'Select'
BEGIN
SELECT *
FROM owner.dbo.MVR_Staging
END
END
to run:
exec UPDATE_STAGING insertnew
GO
Some correction to your code that is not related to your issue, but is good to keep a best practice and clean code.When declaring a stored procedure parameter, there's no point using parenthesis (#StatementType NVARCHAR(20) = ''). Also you should be using ELSE IF #StatementType = 'Select', without ELSE, this second IF condition will always be checked. Execute the procedure exec UPDATE_STAGING 'insertnew', as the parameter is NVARCHAR. As for your real issue, you could try comment the INSERT part and leave only the SELECT to see if rows are returned.

Capturing ##error and ##rowcount from a single query

This seems like it should be pretty simple, but I cannot find a way to do it.
set nocount on;
Update MyTable
set MyField = 'value'
--where 1 = 1/0 -- comment in to test getting an error.
print convert(varchar, ##error)
print "blah blah" + convert(nvarchar, ##rowcount) -- this is always zero because of the previous statement
I tried storing them in a variable, but setting the variable generates a new ##rowcount and new ##error value.
I also tried using an if condition, because i don't care about the row count. But evaluating the if seems to also reset ##rowcount.
You can do it in a single statement, like this:
DECLARE #err INT, #cnt INT
SELECT #err=##ERROR, #cnt=##ROWCOUNT

MSTSQL: Can a SP return both an out param and a result set

I wish to know whether it's feasible to have a TSQL stored procedure return both a result set and the output parameter like so.
create procedure uspReadMyXmlInformation(#myXmlDoc xml, #myProductNum varchar(18) output) as
begin
set nocount on;
declare #myXmlContent table(MyOrderId varchar(12) not null
,CreatedAt datetime not null)
insert into #myXmlContent
select x.c.value('MyOrderID[1]', 'varchar(12)')
x.c.value('CreatedAt[1]', 'datetime')
from #myXmlDoc.nodes('MyRootNodeName/MyChildNodeName') x(c)
set #myProductNum='MyProductNum'
select *
from #myXmlContent
return;
end
So, what happens here is that I can either obtain the result set, when I remove the output parameter, or I obtain the output parameter and the result set is always empty (0=count(*)).
Is there anyway I can obtain both with the same stored procedure or I'd better split them?
I think it's doable from this post in Oracle. I'd like to achieve the same in SQL Server, although constrained to the 2008 version.
Oracle stored procedure: return both result set and out parameters
What I like from doing it using the same SP is that both the result set and the output parameter represent information I read from the XML document. So, the name of the SP says it all, somehow.
EDIT
As some think it might be a duplicate of:
Possible to return an out parameter with a DataReader
I don't think it is as answers there are related as to how the DataReader behaves more than how it could be achieved with TSQL.
The fact is that I get the the value from the output parameter, but I don't get it from the result set at all, it's always returning null.
So, I'm on a SQL Server only project and I'd need that. Otherwise, I'll split it in two, if I can't achieve it in a timely fashion.
Here's how it's used:
declare #xmlInformationData table(MyOrderId varchar(12) not null
,CreatedAt datetime not null)
insert into #xmlInformationData
execute uspReadMyXmlInformation #myXmlDoc, #myProductNum output
while 0<(select count(*) from #xmlInformationData)
begin
-- This will never be executed because I have no rows in #xmlInformationData
-- And yet, before the loop, I have my out param value!
end
The following is a trivial demonstration of using both an output parameter and result set. Try running it a few times and the results should vary.
create procedure Arthur( #TheAnswer as Int Output ) as
begin
-- Set the value of the output parameter.
set #TheAnswer = 42;
-- Generate a single row most of the time.
select GetDate() as NextVogonPoetryReading
where DatePart( millisecond, GetDate() ) < 750;
end;
go 1
-- Declare the variables for the test.
declare #HHGTTU as Table ( HHGTTUId Int Identity, NextVogonPoetryReading DateTime );
declare #SixTimesNine as Int;
-- Execute the SP once so that the while loop might.
insert into #HHGTTU ( NextVogonPoetryReading )
execute Arthur #TheAnswer = #SixTimesNine Output;
-- See what happens.
while exists ( select Pi() from #HHGTTU )
begin
-- See where we are at.
select #SixTimesNine as SixTimesNine, Max( HHGTTUId ) as MaxHHGTTUId, Max( NextVogonPoetryReading ) as MaxNextVogonPoetryReading
from #HHGTTU;
-- Reset.
delete from #HHGTTU;
set #SixTimesNine = 54;
select #SixTimesNine as SixTimesNineAfterReset;
waitfor delay '00:00:00.100';
-- Execute the SP again.
insert into #HHGTTU ( NextVogonPoetryReading )
execute Arthur #TheAnswer = #SixTimesNine Output;
end;
Aside: My apologies for the trauma introduced into your life by my mention of a DataReader. I was merely attempting to pass on my experience in a C# application without getting into the weeds of exactly what sort of connection to the database you are using, which driver(s) might be involved, ... .

Stored procedure to build new queries and a cursor to help execute them - SQL

I am trying to build a stored procedure that takes in values of
#field_name
#some_rule
#from_table
#to_table
and builds up a query. Below is the code from my Stored Procedure:
CREATE PROCEDURE spBuildQuery
#field_name nvarchar(max), -- Will take field name as input
#some_rule nvarchar(max), -- Will take Some rule as a command/input from user
#from_table nvarchar(max), --to take value of table from which value to be taken
#to_table nvarchar(max), --Table where the results should be stored
#final_query nvarchar(max) OUTPUT --Output of final query
AS
IF #some_rule = 'Remove blank rows'
BEGIN
SELECT #final_query = 'SELECT * into temp1 FROM '+#from_table + ' WHERE '+ #field_name+ ' IS NOT NULL'
END
ELSE IF #some_rule = 'Rule2'
BEGIN
SELECT #final_query = 'SELECT * into temp1 FROM'+ #from_table + 'WHERE '+ #field_name+ ' IS RULE2'
END
ELSE
BEGIN
SELECT #final_query = 'Missing Value(s)'
END
--Executing the query by parsing #final_query value into #query and priting it.
DECLARE #query nvarchar(max)
EXECUTE spBuildQuery 'A Field', 'Rule2', 'Table 1', #query OUTPUT
PRINT #query
EXECUTE sp_executesql #query
My intention is to build queries based on user input like: Rules the user wants to implement what field should the rules be applied to and then display the result of that query onto a table, then that Table gets overwritten as new queries are developed. This is my intention, as another approach I was thinking is to save the built up queries into a table column and execute each query line by line using a cursor.
How can I:
a) store the built up queries into a new TEMP table?
b) execute each query using the Cursor (or any other efficient way)?