I am working with classic asp and using stored procedure. I have to get the value of stored procedure out parameter. This is my code
<% #LANGUAGE="VBSCRIPT" CODEPAGE="65001" %>
<!-- METADATA TYPE="TypeLib" NAME="Microsoft ADO Type Library" UUID="{00000205-0000-0010-8000-00AA006D2EA4}" -->
<%
Dim value
Dim i
set con = Server.CreateObject("ADODB.Connection")
con.Open "Provider=SQLOLEDB;Server=aliba\SQLEXPRESS;Database=dummySP;Trusted_Connection=Yes;"
Set Comm = Server.CreateObject("ADODB.Command")
comm.ActiveConnection = con
comm.CommandText = "sp_dummy"
'comm.NamedParameters=true
comm.CommandType = adCmdStoredProc
comm.Parameters.Append comm.CreateParameter("#weight" , adVarchar,adParamInput, 50, "hello")
'comm.Parameters.Append comm.CreateParameter("PRODUCT", adVarchar, adParamInput,50, producttype )
'comm.Parameters.Append comm.CreateParameter("ACCOUNT", adVarchar, adParamInput,100, "" )
comm.Parameters.Append comm.CreateParameter("#pris", adVarchar, adParamOutput,50) 'output parameters
'i=comm.Execute
comm.Execute
value=comm.Parameters("#pris").Value
Response.Write("Value is")
Response.Write(value)
The value of pris is not showing on output.I have no idea what is wrong with this.
I followed this link (Calling SQL Stored Procedure with Output Parameter in VBScript) but does not get success
It is giving me following error
Value is
Response object error 'ASP 0185 : 8002000e'
Missing Default Property
/StoreProcedure.asp, line 0
A default property was not found for the object.
Here is my stored procedure
ALTER procedure [dbo].[sp_dummy]
#weight nvarchar(50),
#pris nvarchar(50)= null out
as
begin
select #pris = pris from sp_dummy_table where weight= #weight
end
I suggest that you close out your SP with a SELECT so you can get the value as from a Recordset.
SELECT OutPRIS=#pris
Then in your ASP code:
Set rsComm = comm.Execute
If Not rsComm.EOF Then
myPRIS = rsComm.Fields("OutPRIS").Value
Else
myPRIS = Null
End If
rsComm.Close
Set rsComm = Nothing
Hope this helps.
Related
I am reading and writing data into an Microsoft Access database using Delphi 11.2 and FireDac.
I'd like to be able to set numeric values in the database to NULL based on the (double) value in delphi.
I am currently reading values as strings from the DB
myQuery.FieldByName('myNumericField').AsString
into my delphi object fields and set double values on application level to NAN if I find empty strings. When I write them back to the DB and the user has not set the value on application level the value is obviously set to NAN in the DB as well, but not to NULL, which would be preferred.
Does anybody know a feasible way to set double / numeric fields to NULL in an (microsoft Access or presumably any other) database via firedac?
Help is much appreciated!
Simplified code samples for update and insert I am currently using
update:
dbMain.ExecSQL('update MyTable set ' + 'myNumericField = :P1 ' + 'where myIDField = :P2', [myDataObject.myDoubleValue, myDataObject.myId]);
insert:
dbMain.ExecSQL
('insert into MyTable(myIDField, myNumericField) '
+ 'values(:P1, :P2)',
[myDataObject.myId, myDataObject.myDoubleValue]);
Try something like this:
var
varValue: Variant;
if IsNan(myDataObject.myDoubleValue) then
varValue := Null
else
varValue := myDataObject.myDoubleValue;
dbMain.ExecSQL('update MyTable set myNumericField = :P1 where myIDField = :P2', [varValue, myDataObject.myId]);
Alternatively:
if IsNan(myDataObject.myDoubleValue) then
dbMain.ExecSQL('update MyTable set myNumericField = NULL where myIDField = :P1', [myDataObject.myId])
else
dbMain.ExecSQL('update MyTable set myNumericField = :P1 where myIDField = :P2', [myDataObject.myDoubleValue, myDataObject.myId]);
Alternatively:
var
Params: TFDParams;
Param: TFDParam;
Params := TFDParams.Create;
try
Param := Params.Add('P1', ftFloat);
if IsNan(myDataObject.myDoubleValue) then
begin
Param.Bound := True;
Param.Clear;
end else
Param.Value := myDataObject.myDoubleValue;
Params.Add('P2', myDataObject.myId);
dbMain.ExecSQL('update MyTable set myNumericField = :P1 where myIDField = :P2', Params);
finally
Params.Free;
end;
I have written a stored procedure which will be called from python. The stored procedure needs to insert the variant data into my table if the id doesn't exist or update the existing variant data where there is a match for the id. The id will be passed the way the variant data is, but for now I am just trying to get it working with a hardcoded id. The stored procedure gets called successfully from python, but then nothing gets inserted or updated in the stored procedure and the stored procedure doesn't give me an error. I am not sure if I am doing something wrong or the...
if exists (select * from my_database_table where my_variant_data:id::varchar = '123456')
... part is being ignored because it isn't supported. I haven't been able to find anything in the documentation to prove or disprove this. Does anyone know?
create or replace procedure my_stored_procedure("variant_data" variant)
returns string
language javascript
strict
execute as owner
as
$$
var insert_update_query = `
if exists (select * from my_database_table where my_variant_data:id::varchar = '123456')
begin
update my_database_table SET my_variant_data = parse_json(:1)) WHERE my_variant_data:id::varchar = '123456'
end
else
begin
insert into my_database_table(my_variant_data) select (parse_json(:1));
end
`
var result = "";
try {
var sql_insert_update_query = snowflake.createStatement({
sqlText: insert_update_query
});
var insert_update_query_result = sql_insert_update_query.execute();
result += "\n Query succeeded";
} catch (err) {
result += "\n Query failed failed: " + err.code + "\n State: " + err.state;
result += "\n Message: " + err.message;
result += "\n Stack Trace:\n" + err.stackTraceTxt;
}
return result;
$$
;
I have tested the insert and update parts of the query in the stored procedure individually and they work fine.
Insert - works as expected.
create or replace procedure my_stored_procedure("variant_data" variant)
returns string
language javascript
strict
execute as owner
as
$$
var sql_command = "insert into my_database_table(my_variant_data) select (parse_json(:1));";
var sql = snowflake.createStatement( {sqlText: sql_command, binds:[JSON.stringify(variant_data)]});
var resultSet = sql.execute();
return sql_command;
$$
;
Update - works as expected.
create or replace procedure my_stored_procedure("variant_data" variant)
returns string
language javascript
strict
execute as owner
as
$$
var sql_command = "UPDATE my_database_table SET my_variant_data = parse_json(:1)) WHERE my_variant_data:id::varchar = '123456'";
var sql = snowflake.createStatement( {sqlText: sql_command, binds:[JSON.stringify(variant_data)]});
var resultSet = sql.execute();
$$
;
Given the CODE executed needs to be valid runs on the console SQL, which this if is not, and it is fundamentally a MERGE command I would suggest flipping the code into a MERGE:
MERGE INTO my_database_table USING my_database_table
ON my_variant_data:id::varchar = '123456'
WHEN MATCHED THEN UPDATE SET my_variant_data = parse_json(:1))
WHEN NOT MATCHED THEN INSERT (my_variant_data) VALUES (parse_json(:1));
otherwise if you are want it in SP space, then I would be inclinded to break the code into a SELECT x INTO varaible FROM blar pattern and then have the IF be in SP and pick between the two blocks of SQL to run. But given it's just a merge, I would again still, do a merge.
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
As the headling says I want to call a stored procedure with parameters.
Below is the VB6-function that
Private Sub TestProcedur()
Dim strSql As String
Dim CPw As rdoQuery
strSql$ = "? = {call Insert_Student(?) }"
Set CPw = gRdoConn.CreateQuery("InsertStudent", strSql)
CPw.rdoParameters(0).Direction = rdParamReturnValue
CPw(1) = "FRANK"
Set mrsR = CPw.OpenResultset()
End Sub
The stored procedure below
CREATE PROCEDURE Insert_Student
#Name VARCHAR(50)
AS
BEGIN
INSERT INTO dbo.Student (Name)
VALUES (#Name)
END
GO
I'm getting a problem when running the function. A ERROR messsage occurs when running the line "CPw.rdoParameters(0).Direction = rdParamReturnValue" that says: Not valid description index"
This page on MSDN should explain it nicely:
http://msdn.microsoft.com/en-us/library/aa240826%28v=VS.60%29.aspx
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