I'm struggling with how to pass datetime parameters into a stored procedure. This is the example I'm working with. I commented out the declaring of the variables, because if I declare them it doesn't let me pass them in when I execute, but if I don't declare them, I can't execute it. Please help!
--The Create Procedure Code
CREATE PROCEDURE users.my_test
AS
--declare #startdatetime datetime = '03-20-2019'
--declare #enddatetime datetime = '05-20-2019'
SELECT datediff(mi,#startdatetime,#enddatetime)
GO
--The execution Code
exec users.my_test
#startdatetime = '03-31-2019', #enddatetime = '07/03/2019'
GO
You can add parameter like this
CREATE PROCEDURE users.my_test
#startdatetime datetime ,
#enddatetime datetime
AS
--declare #startdatetime datetime = '03-20-2019'
--declare #enddatetime datetime = '05-20-2019'
SELECT datediff(mi,#startdatetime,#enddatetime)
GO
Related
Need help on getting query on a text file using stored procedure in db2. I'm very new to this so please help.
Till now i am able to create a file and get get data in created file. But i want a complete query in the file not a single column data.
I have created a Stored Procedure like this
CREATE or replace PROCEDURE SCOPEMASTERP(my_statement varchar(10000))
AUTONOMOUS
BEGIN
DECLARE v_filehandle UTL_FILE.FILE_TYPE;
DECLARE v_dirAlias VARCHAR(50) DEFAULT 'mydir';
DECLARE v_filename VARCHAR(100) DEFAULT 'bluestar_transaction-';
DECLARE v_format VARCHAR(200);
SET v_format = '%s\n';
set v_filename = concat(v_filename, VARCHAR_FORMAT(current_date, 'DD-MM-YYYY'));
set v_filename = concat(v_filename, '.log');
CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY('D:', '/archivelog/asd/');
SET v_filehandle = UTL_FILE.FOPEN(v_dirAlias,v_filename,'a');
CALL UTL_FILE.PUTF(v_filehandle,v_format, my_statement);
CALL DBMS_OUTPUT.PUT_LINE('Wrote to file: ' || v_filename);
CALL UTL_FILE.FCLOSE(v_filehandle);
END
and i have created a trigger inside trigger i am calling stored procedure
CREATE OR REPLACE TRIGGER SCOPEMASTER_Trigger
AFTER INSERT ON SERVEIT.SCOPENAMEMASTER
REFERENCING NEW AS N
FOR EACH ROW
BEGIN ATOMIC
call SCOPEMASTERP(N.SCOPENAMEID);
END
insert statement i am executing
Insert into SERVEIT.SCOPENAMEMASTER (SCOPENAMEID) values (1013)
GO
And file which is creating in "D" drive i am getting
But instead of just getting 1013 i need the complete query in the file
Insert into SERVEIT.SCOPENAMEMASTER (SCOPENAMEID) values (1013)
What changes i need to do please help. Thanks in advance!!
There are no special registers/variables/etc. available in DB2 that provide the SQL statement that is being executed, so what you're asking for is not possible.
So i have written some code that executes an oracle database procedure or function
However, when I run a function I return a varray now i wonder what the mvc application gets from the database (I assume an array because I am using an OParray to execute the function); And how for example i would put these results in a viewbag list
the code that i use to execute the function is as folows
OracleParameter[] OPArray1 = new OracleParameter[] { new OracleParameter(null,OracleDbType.Varchar2, 10000, "9a15493038a7365e9ae4c0cfba1136cf", System.Data.ParameterDirection.Input) };
OracleCommand ODCommand1 = DBCon.StoredProcedureOrFunction("getpresentusers", OPArray1);
You need just convert to DateTimetype (C#)
Try this:
DateTime dateTime = DateTime.ParseExact(ds.Tables[0].Rows[0][0].ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
I have created a mvc4 application with entity framework. Added a entity model in project. Now i have
added a store procedure in model browser and editing import function. There is a option Returns a collection of which contains none,scalers,complex,entities. I am not able to decide which one to choose as my store procedure returns multiple output parameters. If it returns single parameter then i can choose scalers, if table then entities. But it returns more then one output parameter so which one to choose. I am attaching store procedure screen shot.
Your stored procedure uses reference parameters, but doesn't actually return anything. To make a stored procedure return something, end the procedure with a SELECT statement that doesn't set a variable.
So, your code with look something like this:
CREATE PROC [wickedbrains].[uspValidateAdminLogin]
#UserName VARCHAR(50),
#Password VARCHAR(50)
AS
BEGIN
DECLARE #UserId INT = NULL,
#Res INT = 0;
IF EXISTS(SELECT '' FROM tblAdminUser WHERE UserName = #UserName AND Pwd = #Password)
BEGIN
SELECT #UserId = Id FROM tblAdminUser WHERE UserName = #UserName AND Pwd = #Password;
SET #Res = 1;
END
SELECT #UserId, #Res;
END
Once you've fixed your stored procedure, as Ehsan described, you can fix your imported stored procedure after the fact by clicking Get Column Information, then clicking Create New Complex Type.
If you absolutely have to use output parameters, you will have to retrieve the parameters with code as you would with reference parameters used in any other function. The point is that stored procedures that only use output parameters don't have a return type. See this answer for further details: https://stackoverflow.com/a/6193419/12116036
I tried implementing a call to Stored proc and the proc returns ID which will used later.
Everytime I execute I get the out parameter as -1. Below is my sample code:
OleDbCommand sqlStrProc = new OleDbCommand();
sqlStrProc.Connection = dbConn;
sqlStrProc.CommandText = "dbo.insert_test";
sqlStrProc.CommandType = CommandType.StoredProcedure;
sqlStrProc.Parameters.Add("#p_TestID", OleDbType.Integer, 255).Direction = ParameterDirection.Output;
sqlStrProc.Parameters.Add("#p_TestName", OleDbType.VarChar).Value = "Test";
sqlStrProc.Parameters.Add("#p_CreatedBy", OleDbType.VarChar).Value = "Test";
int personID = sqlStrProc.ExecuteNonQuery();
Row.outPersonID = personID;
personID is always -1. What am I doing wrong here. Please help..!!
Below is the stored proc code
CREATE PROCEDURE [dbo].[INSERT_TEST]
#p_TestID int OUTPUT,
#p_TestName varchar (50),
#p_CreatedBy varchar (100)
AS
SET NOCOUNT ON
INSERT INTO Test(
TestName,
CreatedBy)
VALUES
( #p_TestName,
#p_CreatedBy)
SELECT #p_TestID = SCOPE_IDENTITY()
-1 could mean that the stored procedure failed to execute as desired and the transaction was rolled back. You may want to look for any truncation issues since you have different sizes for the 2 input parameters but are using the same input. Also I assume you have proper code to open and close connections etc?
-1 returned value is an error produced during the execution of your SP, this is due to the following reasons:
SP Structure: everytime you are executing the SP it tries to create it again while it already exists. so you have to either make it an ALTER PROCEDURE instead of CREATE PROCEDURE or do the following:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INSERT_TEST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[INSERT_TEST]
GO
CREATE PROCEDURE [dbo].[INSERT_TEST]
#p_TestID int OUTPUT,
#p_TestName varchar (50),
#p_CreatedBy varchar (100)
AS
Database Connection (Table Name and Location): you have to specify withe the OLEDB the ConnectionString that connects you to the write DB. try to test the full Table path; like the following;
INSERT INTO [DATABASENAME].[SHCEMA].[TABELNAME](
Name,
CreatedBy)
VALUES
( #p_TestName,
#p_CreatedBy)
Define your SP as :
CREATE PROCEDURE [NAME]
AS
BEGIN
END
thought it is not a problem, but it is a proper way to write your SPs in terms of connection transactions,
Let me know if it works fine with you :)
Regrads,
S.ANDOURA
I have a stored procedure which returns back a table value.
Here is my stored procedure:
PROCEDURE [GetPermitPendingApproval]
#permitYear int = NULL,
AS
BEGIN
SELECT [p].[ID]
,[p].[PermitNumber]
,[p].[PermitTypeID]
,[p].[ApplicationDate]
,[u].[FirstName]
,[u].[MI]
,[u].[LastName]
,[u].[Suffix]
,[u].[ProfessionalTitle]
,[u].[WorksFor]
FROM [SciCollUser] u
INNER JOIN UserPermit up ON up.[UserID] = u.[ID]
INNER JOIN Permit p ON p.[ID] = [up].[PermitID]
WHERE (#permitYear IS NULL OR p.PermitYear = #permitYear)
ORDER BY [p].[ApplicationDate] ASC;
END
I am not sure whether we have such a way to use PetaPoco to execute a stored procedure and get a returned data as a table? Please help!
As normally I can execute a stored procedure with the follow script but it is not the way I want.
db.Execute("EXEC GetPermitPendingApproval #permitYear=2013");
You need to put a semicolon before EXEC.
var result = db.Fetch<dynamic>(";EXEC GetPermitPendingApproval ##permitYear = #0", 2013);
Answer is probably late, but I hope, that it will be useful for future generations. You should turn EnableAutoSelect option to false on PetaPoco database object db.EnableAutoSelect = false;
Otherwise it will keep adding SELECT NULL FROM [Object] to you sql statement.
It's good, that it's possible to debug PetaPoco sources.I've found this option only because of debugging!
You get List<T> where T is a POCO type with the properties you want to map or a Dynamic
So the actual syntax is:
var result = db.Fetch<dynamic>(";EXEC GetPermitPendingApproval #0", 2013);
or
var result = db.Fetch<dynamic>(";EXEC GetPermitPendingApproval #permitYear",
new {permitYear = 2013});
As of v6.0.344-beta, PetaPoco now supports stored procs natively, so you can do:
var result = db.FetchProc<MyClass>("GetPermitPendingApproval", new { permitYear = 2013 });