Row count of a stored procedure from another stored procedure - c#

I have various stored procedures. I need a stored procedure to execute a stored procedure and then return only the row count (number of returned rows by the called procedure) and I need to receive it in c# code.
What's the best way to do this?

Assuming you are using SQL Server (which is possible from the code snippets), perhaps something like this would work for you:
exec('exec <your stored procedure goes here>; select ##RowCount')
Since you are running SQL Server, I can think of one solution that is not necessarily pretty.
Create a temporary table (table variable if you have a more recent version of SQL Server). Then execute:
exec(`
declare #t table (
<columns go here>
);
insert into #t
exec(''<your exec here>'');
select #rowcount
');
And now that I've said that, I would recommend sp_executesql. This goes something like this:
declare #sql nvarchar(max) = N'exec '+#YOURQUERY + '; set #RowCount = ##RowCount';
exec sp_executesql #sql, N'#RowCount int output', #RowCount = RowCount output;
I spent most of yesterday debugging an arcane condition that arises when you call a stored procedure inside an insert.

You can try this in your child stored procedure :
CREATE PROC PawanXX
(
#a INT
,#b INT OUTPUT
)
AS
BEGIN
SELECT TOP 2 * FROM X
SET #b = ##ROWCOUNT
RETURN #b
END
GO
The main stored procedure where we call all other sps
DECLARE #RC int
DECLARE #a int
DECLARE #b int
EXECUTE #RC = [dbo].[PawanXX]
#a
,#b OUTPUT
SELECT #RC
The output for the same
ProcessName Parent Child
ShareDrafts Job12 Job03
ShareDrafts Job13 Job58
(2 row(s) affected)
2
(1 row(s) affected)

Related

How to get Scope Identity Column while inserting datatable using stored procedure

I'm inserting datatable using stored procedure and created a type table before,
the query is i want to get back all the 'ProdID' that has been inserted in this session.
for the single insertion i can get the scope identity but i want to get all for the recent insertion.
Thanks in advance.
[dbo].[sp_Isert] (#dt_Product Product_Table READONLY, #ProdID int out)
AS
INSERT into tblProduct (Name,Batch,Qty,ExpDate)
SELECT Name, Batch, Qty, ExpDate
FROM #dt_Product;
set #ProdID = Scope_Identity( )
select Scope_Identity( ) ProdID
Do not use scope_identity() - use the output clause instead.
Note that SQL Server does not support table valued parameters as out parameters, meaning the only way to return a record set from a stored procedure is either by using the output clause (not into table) or by executing a select statement.
Also, do not use the sp prefix for stored procedured.
Microsoft is using this prefix for system procedues, so you might get a name collision.
ALTER PROCEDURE [dbo].[stp_Isert] (#dt_Product Product_Table READONLY)
AS
INSERT into tblProduct (Name,Batch,Qty,ExpDate)
OUTPUT Inserted.Id -- This will return a recordset with the inserted ids to the calling application.
SELECT Name, Batch, Qty, ExpDate
FROM #dt_Product;
Update
I've made a sample script for you to check. When I'm running this on my SQL Server instance, I get the expected results:
CREATE TABLE tbl_TestOutputClause (Id int identity(1,1), Col int );
GO
CREATE TYPE udt_TestOutputClauseIntegers AS TABLE (Value int);
GO
CREATE PROCEDURE stp_TestOutputClauseInsert (#Values dbo.udt_TestOutputClauseIntegers READONLY)
AS
INSERT INTO tbl_TestOutputClause(Col)
OUTPUT INSERTED.Id
SELECT Value
FROM #Values;
GO
CREATE PROCEDURE stp_TestOutputClauseGetInsertedValues
AS
DECLARE #Ids AS TABLE (Id int);
DECLARE #Vals dbo.udt_TestOutputClauseIntegers;
INSERT INTO #Vals (Value) VALUES (1), (2), (3);
INSERT INTO #Ids
EXEC stp_TestOutputClauseInsert #Vals;
-- should return three rows with the values 1, 2 and 3.
SELECT *
FROM #Ids;
GO
EXEC stp_TestOutputClauseGetInsertedValues;
-- clean up
DROP TABLE tbl_TestOutputClause;
DROP PROCEDURE stp_TestOutputClauseInsert;
DROP PROCEDURE stp_TestOutputClauseGetInsertedValues
DROP TYPE udt_TestOutputClauseIntegers;

Running stored procedure with alive signal because of time out

I have a stored procedure with custom table data type like this :
CREATE TYPE VALUE_BIGINT AS TABLE (VALUE BIGINT NOT NULL)
and this is the stored procedure code:
CREATE PROCEDURE spCalculate (#EmpIds VALUE_BIGINT READONLY)
AS
BEGIN
SELECT
*,
(ROW_NUMBER() OVER (ORDER BY VALUE)) AS RowIndex
INTO #Tmp
FROM #EmpIds
DECLARE #RowCount = ##ROWCOUNT
DECLARE #I INT = 1
WHILE #I <= #RowCount
BEGIN
--Executing query(about 2 sec long)
--!!!SEND Live Signal To C#!!!
SET #I = #I + 1
END
DROP TABLE #Tmp
END
I know that I can set infinity timeout for this stored procedure to ensure execute success but I don't want do this! Because of network issue. I want to send alive signal or something like this to sure my stored procedure is still running ("SqlCommand be patient don't throw timeout exception")
I know we can do this because SQL Server Management Studio can do this! But how?

How can I call a stored procedure with INSERT using LINQ?

Is there any possible way to execute a non query without having to assign it to a LINQ to SQL class?
Let's say I have this procedure and I want to INSERT only if the Town_Name (UNIQUE CONSTRAINT) is non existent. Otherwise, the UPDATE is executed. This procedure works well and does the job when executed through SQL Server. However, I can't manage to execute it through C# code.
I am trying to avoid using SQL client, as part of my coursework, my little application has to be capable of selecting, inserting / updating and deleting data using LINQ.
The approach I'm taking always results in 0 rows affected.
// Call Procedure.
db.P_SaveClient("000000001M", "Test", "Dummy", null, "+35699999999");
-- Procedure to be executed.
CREATE PROCEDURE Appointment.SaveClient
(
#id NVARCHAR(10),
#firstName NVARCHAR(35),
#lastName NVARCHAR(35),
#tel NVARCHAR(12),
#mob NVARCHAR(12)
)
AS
BEGIN
DECLARE #clientCount TINYINT
SELECT #clientCount = COUNT(Client_ID)
FROM Appointment.Client
WHERE Client_ID = #id
IF #clientCount = 0
BEGIN
INSERT INTO Appointment.Client
VALUES (
#id
, #firstName
, #lastName
, #tel
, #mob
)
END
ELSE
BEGIN
UPDATE Appointment.Client
SET Client_ID = #id
, First_Name = #firstName
, Last_Name = #lastName
, Telephone = #tel
, Mobile = #mob
END
END
Some tutorials I found:
https://www.youtube.com/watch?v=dlXT-vE46sc
https://www.youtube.com/watch?v=-PAMtSwplu8
You're looking for a Merge statement to execute in SQL, which you could call via the stored proc. This will allow you to insert or update depending on whether it was found. It can even return the ID of the record inserted which can save you another query.
Merge Town t
using ( select #Town_Name as 'Town_Name')
src on (src.Town_Name = t.Town_Name )
when NOT MATCHED then
insert (Town_Name) values (src.Town_Name)
output INSERTED.Town_ID
See here for syntax and more examples:
https://msdn.microsoft.com/en-us/library/bb510625.aspx

Insert list of values into a SQL Server table with stored procedure

How can I pass a list of column data into a stored procedure?
My stored procedure is
ALTER PROCEDURE [dbo].[Register]
#Id int,
#Name nvarchar(50)
AS
BEGIN
BEGIN TRY
INSERT INTO dbo.Group (Id, Name)
VALUES(#Id, #Name)
SELECT 0
END TRY
BEGIN CATCH
SELECT -1
END CATCH
END
GO
I want pass like this data for insert into this table
#Id = 1,2,3,4,5
#Name = 'test1,test2,test3,test4,test5'
and result like this
Id Name
1 test1
2 test2
3 test3
4 test4
5 test5
A "list" or "array" in SQL Server is ..... a table. So if you're on SQL Server 2008 or newer (you didn't specify), then use the table-valued parameter feature of SQL Server to pass a table of value to your stored procedure
-- Create a table type to match your input parameters
CREATE TYPE IdNameTable AS TABLE
( ID INT, Name NVARCHAR(50) );
GO
-- change your stored procedure to accept such a table type parameter
ALTER PROCEDURE [dbo].[Register]
#Values IdNameTable READONLY
AS
BEGIN
BEGIN TRY
INSERT INTO dbo.Group (Id, Name)
-- get the values from the table type parameter
SELECT
Id, Name
FROM
#Values
SELECT 0
END TRY
BEGIN CATCH
SELECT -1
END CATCH
END
GO
See the extensive and freely available SQL Server Books Online documentation for more details on the table-valued parameter feature and how to use it
If you want to use this from T-SQL, use this code:
-- declare a variable of that table type
DECLARE #InputTable IdNameTable
-- insert values into that table variable
INSERT INTO #InputTable(ID, Name)
VALUES (1, 'Test 1'), (2, 'Test 2')
-- execute your stored procedure with this table as input parameter
EXECUTE [dbo].[Register] #InputTable
If you want to use this from C# or VB.NET, see Michael Edenfield's link in comments.

Convert user-defined function to stored procedure for EF

This is my user-defined function used in a project:
CREATE FUNCTION [dbo].[Encrypt]
(
#Password nvarchar(4000)
)
RETURNS varbinary(4000)
AS
BEGIN
SELECT #Password = CONVERT(nvarchar(4000),#Password);
RETURN HashBytes('SHA1', #Password);
END
GO
I need Entity Framework so, it's possible find a way to convert this one in a stored procedure in SQL Server 2012 Express?
Procedure Definition
CREATE PROCEDURE [dbo].[usp_Encrypt]
#Password nvarchar(4000),
#HashedPass varbinary(4000) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #HashedPass = HashBytes('SHA1',CONVERT(nvarchar(4000),#Password));
END
EXECUTE PROCEDURE
DECLARE #RtnHashedPass varbinary(4000);
EXECUTE [dbo].[usp_Encrypt]
#Password = 'myPassword'
#HashedPass = #RtnHashedPass OUTPUT
SELECT #RtnHashedPass --<-- Do what ever you want to do with this value

Categories