Stored procedure parameter default value - stored-procedures

I'm trying to create a stored procedure with default parameters, in my query I would do it like this:
DECLARE #mydate DATETIME
DECLARE #MT DATETIME
DECLARE #MY DATETIME
SELECT #mydate = GETDATE()
SELECT #MT = DATEPART(MONTH,#mydate)
SELECT #MY = DATEPART(YEAR,#mydate)
SELECT * FROM ....
In my stored proc I've tried it as follows but when I execute the stored proc it prompts me for parameter values:
USE ..
GO
..
ALTER PROCEDURE ...
(#mydate DATETIME
,#MT DATETIME
,#MY DATETIME)
AS
BEGIN ...
SELECT #mydate = GETDATE()
SELECT #MT = DATEPART(MONTH,#mydate)
SELECT #MY = DATEPART(YEAR,#mydate)
---
SELECT * FROM ....
How do I set the parameter values in the stored proc like I would in the query?

Try this..
I put only one parameter because the others depend on it.
First approach
USE ..
GO
..
ALTER PROCEDURE yourSP
(#mydateParam DATETIME)
AS
BEGIN ...
SELECT #mydate = #mydateParam
SELECT #MT = DATEPART(MONTH,#mydate)
SELECT #MY = DATEPART(YEAR,#mydate)
---
SELECT * FROM ....
To call the SP:
DECLARE #mydateParam DATETIME
SELECT #mydateParam = GETDATE()
execute yourSP #mydateParam
Second approach
ALTER Procedure yourSP
#mydateParam datetime = null
AS
BEGIN ...
IF #mydateParam is null
SET #mydateParam = getdate()
SELECT #mydate = #mydateParam
SELECT #MT = DATEPART(MONTH,#mydate)
SELECT #MY = DATEPART(YEAR,#mydate)
---
SELECT * FROM ....
To call the SP:
DECLARE #mydateParam DATETIME
SELECT #mydateParam = GETDATE()
execute yourSP #mydateParam
or
execute yourSP

Related

update a column inside a stored procedure

I have two snowflake tables as below
TEST1
create OR REPLACE table TEST1 (
id varchar(100),
name varchar(100),
org VARCHAR(64)
);
INSERT INTO TEST1 values (100, 'ABC', null);
INSERT INTO TEST1 values (200, 'XYZ', null);
INSERT INTO TEST1 values (300, 'VBN', null);
CONTROL
create OR REPLACE table CONTROL (
KEY_COLUMNS VARCHAR,
TABLE_NAME VARCHAR,
org VARCHAR
);
INSERT INTO CONTROL values ('id,name, address','TEST1','Z');
INSERT INTO CONTROL values ('id,name, address','TEST2','T');
I have created a stored procedure which updates column 'org' in TEST1 table with the values from CONTROL table (column org) where table name is TEST1.
CREATE OR REPLACE PROCEDURE TEST(source_tbl VARCHAR)
RETURNS string
LANGUAGE SQL
AS
$$
DECLARE
query1 STRING;
BEGIN
QUERY1 := 'update TEST1 set ORG = (select org from CONTROL WHERE TABLE_NAME = ''source_tbl'');';
EXECUTE IMMEDIATE :QUERY1;
RETURN :QUERY1;
END;
$$;
call TEST((select TABLE_NAME from CONTROL WHERE TABLE_NAME = 'TEST1'));
expected output
My output
The parameter should be bound variable instead of passing as the string constant ''source_tbl'':
CREATE OR REPLACE PROCEDURE TEST(source_tbl VARCHAR)
RETURNS string
LANGUAGE SQL
AS
$$
DECLARE
query1 STRING;
BEGIN
QUERY1 := 'update TEST1 set ORG = (select org from CONTROL WHERE TABLE_NAME = ?);';
EXECUTE IMMEDIATE :QUERY1 USING (SOURCE_TBL);
RETURN :QUERY1;
END;
$$
Related: EXECUTE IMMEDIATE:
EXECUTE IMMEDIATE '<string_literal>'
[ USING (bind_variable_1 [, bind_variable_2 ...] ) ] ;

Snowflake Stored Procedure Not Inserting Record Though No Error

Can someone tell me why this would run but not actually insert a record? When I return the actual query as a variable the code works perfectly in Snowflake:
CREATE OR REPLACE PROCEDURE Z_PC_FIVETRAN_DB.BLOB_RAW_CATALOGS.SP_FULL_AND_IS_HERRING_MOVE_CURRENT_DELETED_TO_PCFIVE(ACTION_TYPE VARCHAR,UPLOAD_ID VARCHAR,VENDOR VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
var sql_textA = "INSERT INTO Z_PC_FIVETRAN_DB.BLOB_RAW_CATALOGS.RAW_CATALOGS (M_PDT_CODE) SELECT M_PDT_CODE FROM Z_CATALOGS_NEW.PUBLIC.CATALOGS_RAW WHERE M_VENDOR_NAME='HERRING' AND M_PDT_CODE NOT IN (SELECT M_PDT_CODE FROM Z_PC_FIVETRAN_DB.BLOB_RAW_CATALOGS.RAW_CATALOGS WHERE M_UPLOAD_ID='" +UPLOAD_ID+ "' AND M_PDT_CODE IS NOT NULL)"
var sql_commandA = snowflake.createStatement({ sqlText: sql_textA})
if (VENDOR=='HERRING' && ACTION_TYPE=='FULL')
{
var db = sql_commandA.execute()
return sql_textA
}
else
{
return 'Not HERRING Or Not FULL'
}
$$;
I ran your code and am able to insert rows. Only thing I can think of is if AUTOCOMMIT is turned off for you and if you need to explicitly call COMMIT. Try to call COMMIT after the INSERT and see if it works.
ALTER SESSION SET AUTOCOMMIT = FALSE;
CREATE OR REPLACE TABLE CATALOGS_RAW(M_VENDOR_NAME VARCHAR, M_PDT_CODE VARCHAR);
CREATE TABLE RAW_CATALOGS(M_PDT_CODE VARCHAR,M_UPLOAD_ID VARCHAR);
INSERT INTO CATALOGS_RAW VALUES('HERRING','PDT0002');
INSERT INTO CATALOGS_RAW VALUES('HERRING','PDT0003');
INSERT INTO CATALOGS_RAW VALUES('HERRING','PDT0005');
COMMIT;
SELECT * FROM CATALOGS_RAW;
INSERT INTO RAW_CATALOGS VALUES('PDT0001','UPD0001');
SELECT * FROM RAW_CATALOGS;
CREATE OR REPLACE PROCEDURE TESTPROC(ACTION_TYPE VARCHAR,UPLOAD_ID VARCHAR,VENDOR VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
var sql_textA = "INSERT INTO RAW_CATALOGS (M_PDT_CODE) SELECT M_PDT_CODE FROM CATALOGS_RAW WHERE M_VENDOR_NAME='HERRING' AND M_PDT_CODE NOT IN (SELECT M_PDT_CODE FROM RAW_CATALOGS WHERE M_UPLOAD_ID='" +UPLOAD_ID+ "' AND M_PDT_CODE IS NOT NULL)"
var sql_commandA = snowflake.createStatement({ sqlText: sql_textA})
if (VENDOR=='HERRING' && ACTION_TYPE=='FULL')
{
var db = sql_commandA.execute()
return sql_textA
}
else
{
return 'Not HERRING Or Not FULL'
}
$$;
CALL TESTPROC('FULL','UPD0003','HERRING');
COMMIT;

function or stored procedure for bulk insert in table by sets

how can i convert the following to teradata stored procedure or some function :
WHILE EXISTS (SELECT * FROM #temp_set1)
BEGIN
/*group of statemnts :delete insert etc
like */
INSERT INTO #temp_set
SELECT TOP 200 * FROM #temp_set1;
INSERT INTO Activepull
as select * from #temp_set1
and this should occur for each set of 200 untill all inserts
end;
There are more than 60000 rows in #temp_set1 so want to insert by sets.
Thanks.
Written on my phone, but I would use the over expression. It creates a kind of pseudo Identity column that you can then use to paginate. And you can even choose the order based on an order by clause.
Declare #IntervalSize int = 100
Declare #BeginSet int = 0,
#EndSet int = #IntervalSize
While #Counter < (Select Max(ROW_NUMBER() OVER (ORDER BY someColumn desc) From #temp_set1)
Begin
Insert Into #temp_set
Select *, Row_Number() Over (Order By someColumn desc) As MyIdentity
Where MyIdentity Between #BeginSet And #EndSet
Select #BeginSet = #BeginSet + #IntervalSize,
#EndSet = #EndSet + #IntervalSize
End

Firebird stored procedure always returning zero

This is my stored procedure:
SET TERM ^ ;
CREATE PROCEDURE INSERT_ETYPE (
E_ID Integer,
E_NAME Varchar(20) CHARACTER SET NONE )
RETURNS (
NEW_ID Integer)
AS
declare variable addr varchar(20);
declare variable type smallint;
declare variable ord smallint;
declare variable cmd varchar(255);
declare variable answr varchar(255);
begin
insert into ETYPE
select * from ETYPE where ID=:e_id;
select max(ID) from ETYPE into :new_id;
update ETYPE set NAME = :e_name where ID = :new_id;
for
select ADDR,REGTYPE,ORD from ETYPEREGS
where ETYPE_ID=:e_id
into :addr,:type,:ord
do
begin
insert into ETYPEREGS
(ETYPE_ID,ADDR,REGTYPE,ORD)
values
(:new_id,:addr,:type,:ord);
end
for
select CMD,ANSWR,ORD,REGTYPE from ETYPESPECIAL
where ETYPE_ID=:e_id
into :cmd,:answr,:ord,:type
do
begin
insert into ETYPESPECIAL
(ETYPE_ID,CMD,ANSWR,ORD,REGTYPE)
values
(:new_id,:cmd,:answr,:ord,:type);
end
end^
SET TERM ; ^
This is my code in C++:
StoredProc_InsertEType->ParamByName("E_ID")->AsInteger = src_id;
StoredProc_InsertEType->ParamByName("E_NAME")->AsString = _name;
try
{
StoredProc_InsertEType->ExecProc();
new_id = StoredProc_InsertEType->ParamByName(L"NEW_ID")->AsInteger;
}
catch(EDBEngineError & e)
{
errors->Add(e.Message);
return false;
}
Variable new_id is always zero regardless of fact that table ETYPE is not empty. When I run command SELECT MAX(ID) FROM ETYPE from administration tool FlameRobin it returns correct number (~180). What should I do to obtain correct value of NEW_ID parameter?
you need to add
suspend;
in your sp
and query with
select * from your_sp
suspend explained
http://www.janus-software.com/fbmanual/manual.php?book=psql&topic=104
regards,

insert multi value with SP

I have two tables.
1- student table & 2- Score table
I want to insert value at student table & insert multi value at Score table with SP to SQL Server 2008.
for EX:
ALTER proc [dbo].[InsertIntoScore]
(
#DateReg datetime,
#stdLastName nvarchar(50),
#stdFirstName nvarchar(50),
#Description nvarchar(500),
multi value as score table...
)
AS
DECLARE #Id AS INT
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Student(DateReg,stdLastName,stdFirstName,[Description])
VALUES (#DateReg,#stdLastName,#stdFirstName,#Description)
set #Id = SCOPE_IDENTITY()
insert multi value at Score table...
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK
END CATCH
please help me...
You should use Table-Valued Parameters
Create a Sql Type for the table you will pass in
CREATE TYPE dbo.ScoreType AS TABLE ( ScoreID int, StudentID int, etc.... )
pass your datatable from C# code into the stored procedure using the above defined type
ALTER proc [dbo].[InsertIntoScore]
( #DateReg datetime, #stdLastName nvarchar(50), #stdFirstName nvarchar(50),
#Description nvarchar(500), #tvpScore ScoreType)
AS
.....
INSERT INTO dbo.Score (ScoreID, StudentID, ....)
SELECT dt.ScoreID, #id, .... FROM #tvpScore AS dt;
in c# pass the datatable in this way
SqlCommand insertCommand = new SqlCommand("InsertIntoScore", sqlConnection);
SqlParameter p1 = insertCommand.Parameters.AddWithValue("#tvpScore", dtScore);
p1.SqlDbType = SqlDbType.Structured;
p1.TypeName = "dbo.ScoreType";
.....
insertCommand.ExecuteNonQuery();

Resources