I have a stored procedure:
CREATE PROCEDURE [dbo].[usp_SelectStuff] AS
#param1 int
#param2 int
BEGIN
SELECT [Stuff] FROM TABLE
END
I want to run this from SubSonic, and the use the stuff that has been selected. So I do:
var db = DB.CreateDB();
var stuffProcedure = db.UspSelectStuff(0,1);
Now how do I actually get the data from here?
You can also load a collection and match properties will be populated:
ProductCollection coll = new ProductCollection();
coll.LoadAndCloseReader(db.UspSelectStuff(0, 1).GetReader());
You have to execute the stored procedure as a data set:
var stuffProcedure = db.UspSelectStuff(0, 1).GetDataSet();
Related
I am writing below Stored Procedure in BigQuery but not sure where did I do wrong.
The 'Out' Parameter does not return anything.
Stored Procedure:
create procedure if not exists test.GetNumTherapistSessions(
in LastNamee string,
out NumSessione int64
)
begin
select count(s.SessionNum) as NumSession from test.Session s
inner join test.Therapist t on s.TherapistID=t.TherapistID
where t.LastName=LastNamee;
end
and Here is how I declare the output parameter and how to call it:
declare NumSession int64;
call test.GetNumTherapistSessions("Risk",NumSession);
Here is the output:
So far everything seems right, but when I select the NumSession, it returns Null:
select NumSession;
Output:
Try SET NumSessione = (select count...);
create procedure if not exists test.GetNumTherapistSessions(
in LastNamee string,
out NumSessione int64
)
begin
SET NumSessione = (
select count(s.SessionNum) as NumSession from test.Session s
inner join test.Therapist t on s.TherapistID=t.TherapistID
where t.LastName=LastNamee
);
end
As shown in this docs of bigquery Link you can use SET to assign any values you need to a specific Variables.
Note that bigquery don't have SELECT INTO statement inside procedure.
Examples:
SET (value1, value2, value3) = (SELECT AS STRUCT c1, c2, c3 FROM table_name WHERE condition)
From this answer:select-into-with-bigquery
Another Example:
UPDATE dataset.Inventory
SET quantity = quantity +
(SELECT quantity FROM dataset.NewArrivals
WHERE Inventory.product = NewArrivals.product),
supply_constrained = false
WHERE product IN (SELECT product FROM dataset.NewArrivals)
Another examples can be found here: Link
I have a stored procedure whose return I want to access, using the Coldfusion cfstoredproc tag. However, the return variable is not listed as an out param, along with the 6 "in" params. See procedure's code below:
CREATE PROCEDURE [dbo].[sp_Hire_AddEVerifyEmpCloseCase]
(
#e_verify_id bigint
,#ClientSftwrVer varchar(30)=null
,#CaseNbr char(15)
,#CloseStatus varchar(50)
,#CurrentlyEmployed varchar(1)
,#submit_user_id int
//THIS LINE IS MISSING: #EmpCloseCase_Id int OUTPUT
)
AS
BEGIN
DECLARE #EmpCloseCase_id int
SET #EmpCloseCase_id=0
SELECT #EmpCloseCase_id = EmpCloseCase_id FROM Appl_Hired_EVerify_EmpCloseCase WITH(NOLOCK) WHERE e_verify_id = #e_verify_id
BEGIN TRANSACTION EmpCloseCase
BEGIN TRY
IF(#EmpCloseCase_id = 0) BEGIN
INSERT INTO Appl_Hired_EVerify_EmpCloseCase(e_verify_id,ClientSftwrVer,CaseNbr,CloseStatus,CurrentlyEmployed, systemdate,submit_user_id)
VALUES (#e_verify_id,#ClientSftwrVer,#CaseNbr,#CloseStatus,#CurrentlyEmployed,GETDATE(),#submit_user_id)
SET #EmpCloseCase_id=ISNULL(SCOPE_IDENTITY(),0)
END ELSE BEGIN
UPDATE Appl_Hired_EVerify_EmpCloseCase
SET ClientSftwrVer = #ClientSftwrVer,
CaseNbr = #CaseNbr,
CloseStatus = #CloseStatus,
CurrentlyEmployed = #CurrentlyEmployed,
systemdate = GETDATE(),
submit_user_id = #submit_user_id
WHERE EmpCloseCase_id = #EmpCloseCase_id
END
COMMIT TRANSACTION EmpCloseCase
END TRY
BEGIN CATCH
SET #EmpCloseCase_id=0
ROLLBACK TRANSACTION EmpCloseCase
END CATCH
RETURN #EmpCloseCase_id
END
Because that "OUTPUT" line is missing, it throws an error if I try to include <cfprocparam type="out" variable="empCloseCaseId"> in my cfstoredproc. Is there any way to access/store the value of this return variable #EmpCloseCase_id, using cfstoredproc, without having to add in that missing "OUTPUT" line or otherwise change the proc's code?
Change
RETURN #EmpCloseCase_id
to
SELECT #EmpCloseCase_id as emp_close_case_id
and in your cfstoredproc call, add
<cfprocresult name="foo">
This defines the variable foo as a query with a single row and a column emp_close_case_id.
<cfoutput>
#foo.emp_close_case_id#
</cfoutput>
EDIT: No way to access that data without properly declaring the output variable or returning a data set with a select statement. SQL Server docs: Return Data from a Stored Procedure
I have a stored procedure, in which I want to simply store result of a select statement in an output parameter and return that , how can i do that.
I would appreciate if you give me the right syntax of it, since i am new to DB and Sybase specially, that's why i am just giving u a pseudo code for that..
/pseudo code
create my_proc(in_param i,out_param o1,out_param o2){
.....other select and insert statements
.....
if(xyz=true){
o1 = select * from emplyees
}
return o1,o2
}
You don't need output parameters to return result of query, try below code
create procedure proc1
(
#val1 integer
)
as
begin
select * from emplyees
end
/pseudo code
create my_proc(in_param int,out_param1 int out,out_param2 int out)
BEGIN
.....other select and insert statements
if(xyz=true)BEGIN
select out_param1=e.col1,out_param1=2=e.col2 from emplyees e
END
END
Modify datatypes accordingly
Thanks,
Gopal
I have a stored procedure in my database that takes a table value parameter, a list of IdTable objects which contain a single integer Id column.
I have an entity model for the database and want to do the following...
ProjectEntities projectEntities = new ProjectEntities ();
DataTable stationIds = new DataTable();
stationIds.Columns.Add("Id");
stationIds.Rows.Add(1);
stationIds.Rows.Add(2);
SqlParameter parameter = new SqlParameter("#stationIds",stationIds);
parameter.TypeName = "IdTable";
var parameters = new object[] {parameter};
var results = projectEntities .ExecuteStoreQuery<ProjectSummary>("exec ProjectSummary", parameters);
var count = results.Count();
This runs and returns no results, when it should return a bunch of ProjectSummary entities.
When I profile this in SQL Profiler, I get the following
declare #p3 IdTable
insert into #p3 values(N'1')
insert into #p3 values(N'2')
exec sp_executesql N'exec ProjectSummary',N'#stationIds [IdTable] READONLY',#stationIds=#p3
If I declare the stored procedure to be
ALTER PROCEDURE [dbo].[ProjectSummary]
#stationIds [dbo].[IdTable] READONLY
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT * FROM #stationIds
...
Then I get not results back, it looks like the TVP parameter is coming through empty.
Where as if I manually execute
declare #p3 IdTable
insert into #p3 values(N'1')
insert into #p3 values(N'2')
EXEC [ProjectSummary]
#stationIds = #p3
GO
I get the values 1 and 2 returned from the SELECT query.
So, it looks like I want to use EXEC rather than SP_EXECUTESQL when I run ExecuteStoreCommand. Given the code example above, how on earth do I do that?
Turns out the ExecuteStoreQuery call was incorrect, it should be
SqlParameter stations = new SqlParameter { ParameterName = "p0", Value = ids, TypeName = "[dbo].[IdTable]", SqlDbType = SqlDbType.Structured };
var parameters = new object[] { stations };
var results = projectEntities.ExecuteStoreQuery<ProjectSummary>("exec ProjectSummary #p0", parameters);
So I needed to name parameter and add the #p0 to the exec command.
Here's my SQL Server stored procedure :
ALTER PROCEDURE [dbo].[SearchUser]
(#Text NVARCHAR(100),
#TotalRows INT = 0 OUTPUT)
AS
BEGIN
SELECT #TotalRows=1000
SELECT * from Users
END
And my C# code
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
Response.Write(outputParameter.Value);
}
However outputParameter.Value always is null.
Could anybody tell me why?
Output parameters filled by its actual values during the execution of the stored procedure.
But table-valued stored procedure actually get executed only in moment when you're trying to iterate resulting recordset, but not calling a wrapper method.
So, this DOES'T work:
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
// Paremeter value is null, because the stored procedure haven't been executed
Response.Write(outputParameter.Value);
}
This DOES:
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
// Procedure does not executes here, we just receive a reference to the output parameter
var results = context.SearchUser("", outputParameter);
// Forcing procedure execution
results.ToList();
// Parameter has it's actual value
Response.Write(outputParameter.Value);
}
When you're working with stored procedures what don't return any recordset, they execute immediately after a method call, so you have actual value in output parameter.
We had a simular issue due to defered excecution our unit tests failed. In short if you have a stored proc that does NOT return anything you need to be sure to set the response type as 'None' when set as 'None' it will be excecuted when called and not defered.
In case you return anything (E.g. Scalar type of String results) it will excecute it when you use the result even if that .Count() or .ToList() is outside of the method that contains the function call.
So try not to force excecution if not need, when needed it should excecute but be sure to declare it correctly or it might not work.
I have same problem before. The main reason I think that the entities framework has the bug in case the user stored procedure has output parameter and return a result set. For example:
ALTER PROCEDURE [dbo].[SearchTest]
(
#RowTotal INT = 0 OUTPUT,
#RowCount INT = 0 OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
SELECT * FROM SomeThing
SELECT #RowTotal = 1233, #RowCount = 5343
END
However if you change the user stored procedure as following, you can get the output params
ALTER PROCEDURE [dbo].[SearchTest]
(
#RowTotal INT = 0 OUTPUT,
#RowCount INT = 0 OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
SELECT #RowTotal = 1233, #RowCount = 5343
END
You can workaround as following:
ALTER PROCEDURE [dbo].[SearchTest]
AS
BEGIN
DECLARE #RowTotal INT, #RowCount INT
SET NOCOUNT ON
SELECT #RowTotal = 1233, #RowCount = 5343
SELECT #RowTotal AS RowTotal, #RowCount AS RowCount, s.*
FROM SomeThing s
END
If anybody has better solution, please tell me