Executing a SQL Server stored procedure from a historian calculation - stored-procedures

Using Historian 5.5 and SQL Server 2012.
I have a stored procedure in SQL Server called perfEng_RWtopits and I want to call this procedure from within a calculation tag in Historian Administrator.
The stored procedure returns one float value.
I have the following code so far:
Dim sql
Dim con
Dim cmd
Dim value
sql = "perfEng_RWtopits"
Set con = CreateObject("ADODB.Connection")
con.ConnectionString = "myconnectionstring"
con.Open
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandText = sql
value = cmd.Execute
con.close
Set cmd = Nothing
Set con = Nothing
When I test the calculation I get a value of zero and a quality of bad. If I execute the stored procedure within SQL Server I get 17.123554 (which is correct). Also if I add the following to the end.
Result = value
I get the following error message.
Can anyone help?

You have an error in your vb script. To bad that we can't debug that in Historian Administrator in calcullation tab.
When using a parameterless function you can execute it by writing:
FunctionName
or
FunctionName(), but when you want to pass the result to a variable then you must use () like this value = FunctionName().
You are using function cmd.Execute without () and returning the result to value. Just fix the line
value = cmd.Execute
to
value = cmd.Execute()

Related

Conversion failed because the DateTime data value overflowed the type specified for the DateTime value part in the consumer's buffer

i have a stored procedure in Sybase ASE with date params in it, so when i created a OLE DB Connection and passing the date parameters to the OLE DB Command,And we are mapping to the parameter with OLEDBType.DBTimeStamp type, datetime param type in stored procedure is smalldatetime.
Here is the sample code.
OLEDBConnection con = new OLEDBConnection(connectionstring);
con.open;
OLEDBCommand cmd = new OLEDBCommand(con);
cmd.QueryString = "dbo.job_xb_new"
cmd.QueryType = "Stored Procedure";
cmd.Parameters.Add("#signoff",OLEType.DBTimeStamp);
cmd.Parameters("#signoff").Value = Datetime.now;
cmd.executeNonQuery(); -----------> ERROR HERE
while executing the store-procedure i am receiving the error.
"Conversion failed because the DateTime data value overflowed the type specified for the DateTime value part in the consumer's buffer" ?
Please help!!!
With the only information given there may be a solution to try.
Change the datatype of your input value to the stored proc to a char/varchar
create procedure dbo.myProc
#inDate varchar(20)
AS
BEGIN
..
END
Perform internal conversion from that with CONVERT before passing to your query.
SET #inDate = CONVERT(datetime,#inDate,[style parameter number])
For troubleshooting, just comment out everything in the procedure and SELECT #inDate first to determine what the data coming in from the OLE DB app looks like. You may be in for a surprise there...

Can't pass a string to a stored procedure

Here's my stored procedure...
alter PROCEDURE ReplyToEmailConfirmation
#uniqueKey varchar(36)
AS
BEGIN
Print 'Hello World!'
END
Here's the code...
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
.ActiveConnection = getConfigValue("ASPClassicConnectionString")
.CommandType = adCmdStoredProc
.CommandText = "[ReplyToEmailConfirmation]"
.Parameters.Append .CreateParameter("#uniqueKey", adVarChar, adParamInput, 36, "dc8d8bfd-ea3a-4ad9-9f2d-92831eb2655a")
End With
cmd.Execute
Here's the error...
ADODB.Command error '800a0bb9'
Arguments are of the wrong type, are out of acceptable range, or are
in conflict with one another.
How do I get this to work? The intention is to use adGUID, but I figured I'd try adVarChar to narrow down the error.
If you read the documentation for CreateParameter() all becomes clear;
If you specify a variable-length data type in the Type argument, you must either pass a Size argument or set the Size property of the Parameter object before appending it to the Parameters collection; otherwise, an error occurs.
As you are passing a VARCHAR which is a "variable-length" data type you have to specify Size when calling CreateParameter().
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
'Let the cmd deal with the connection.
.ActiveConnection = getConfigValue("ASPClassicConnectionString")
.CommandText = "[ReplyToEmailConfirmation]"
.CommandType = adCmdStoredProc
Call .Parameters.Append(.CreateParameter("#uniqueKey", adVarChar, adParamInput, 100))
.Parameters("#uniqueKey") = "dc8d8bfd-ea3a-4ad9-9f2d-92831eb2655a"
End With
Call cmd.Execute()
'Tidy up memory
Set cmd = Nothing
Also included CommandType of adCmdStoredProc which tells ADO to interpret this command as a Stored Procedure call, without it the default is adCmdUnknown which means ADO has to attempt to workout what the command is, which however small adds an unnecessary overhead.
Also not a big fan of instantiating the ADODB.Connection object just to execute a ADO.Command object which then means you have to manage closing the ADODB.Connection yourself. Instead let the ADODB.Command do it for you, by passing a connection string letting it create the connection and destroy it itself. Assuming getConfigValue("ASPClassicConnectionString") returns a connection string you can pass it directly to ActiveConnection and the ADODB.Command will instantiate the connection and dispose of it.
Useful Links
A: Passing Parameters to a Stored Procedure using ASP (Explains how to use METADATA to include Named Constants)
I didn't include adovbs.inc for the adCmdStoredProc, adVarChar and adGUID constants. Doh.

How to check whether stored procedure executed successfully

If you have a stored procedure that executing multiple queries, doesn't return values and doesn't have error-handling in it, how can you ascertain whether the stored procedure ended successfully when calling from VB code?
For example, if the stored procedure is something like:
create stored procedure some_procedure
Insert into ...
delete ...
update ...
end
... and the VB code is like this:
Cmd.ActiveConnection = cn
Cmd.CommandText = "some_procedure"
Cmd.CommandType = adCmdStoredProc
Set rs = Cmd.Execute
Debug.Print rs(0)
... then how can I get a return value that is 0 for success or 1 for failure?
I believe passing the optional RecordsAffected parameter with the Execute statement will work for you. Since you're so scarce on the details you'll have to try it, but this has worked for me with SQL, and FoxPro OLEDB providers. Also, why no error handling? IMHO not having an error handler in code that has a good possibility of producing an error is asking for trouble.
...
Dim lngRecsAffctd As Long
Cmd.ActiveConnection = cn
Cmd.CommandText = "some_procedure"
Cmd.CommandType = adCmdStoredProc
Cmd.Execute lngRecsAffctd, ,adCmdStoredProc 'why set to a recordset when the sproc doesn't return anything?
Debug.Print lngRecsAffctd
...
The complete details of the Execute command and the RecordsAffected parameter can be found at msdn.microsoft.com/en-us/library/ms681559%28v=vs.85%29.aspx

Script always throws an error if CREATE/ALTER is not first statement

I am getting an error when I try to execute the script that is given at end of this post. My requirement is to check for procedure's existence, then drop it if it exists and finally create the procedure.
How would I do this using a single script file?
Procedure Proc_GenerateTestData. 'CREATE/ALTER PROCEDURE' must be the first statement in a query batch. SQL2.sql 12 1
The SQL script that always throws above error is as below.
IF OBJECT_ID('dbo.Proc_GenerateTestData', 'p') IS NOT NULL
BEGIN
DROP PROCEDURE dbo.Proc_GenerateTestData
END
CREATE PROCEDURE dbo.Proc_GenerateTestData #numberOfRecords INT = 100
AS
--drop table #temp1
DECLARE #currentTime AS TIME = CAST(GETDATE() AS TIME);
DECLARE #currentWorkShiftDate AS DATETIME = CAST(CAST(GETDATE() AS DATE) AS DATETIME);
DECLARE #startTime TIME,
#lastShiftStartTime TIME;
DECLARE #tenantId AS UNIQUEIDENTIFIER = (SELECT TOP (1)
Tenants.Id
FROM Tenants
ORDER BY Tenants.Id ASC);
DECLARE #workshiftId INT,
#lastShiftStartDate DATETIME;
--more statements for this procedure follow
As the error clearly says - the CREATE PROCEDURE must be the first statement in a query batch.
This is not the case here, since you have the check for the DROP before hand.
You need to change your script so that the CREATE PROCEDURE statement is really the first in the query batch. If you're running this in SQL Server Management Studio, just add a GO delimiter before the CREATE.

How to execute SubSonic3 StoredProcedure with return value

How do I execute a SP and get the return value. The below code always returns null object. The storedprocedure has been tested in the database using the same parameters as in code, but the SubSonic sp always returns null. When executed in the db via sql, it returns the correct values.
This is using SubSonic 3.0.0.3.
myDB db = new myDB();
StoredProcedure sp = db.GetReturnValue(myParameterValue);
sp.Execute();
int? myReturnValue = (int?)sp.Output;
In the above code, sp.Output is always null. When executed in the database, the returned variable is a valid integer (0 or higher) and is never null.
Stored procedure code below:
CREATE PROCEDURE [dbo].[GetReturnValue]
#myVariable varchar(50)
AS
declare #myReturn int
BEGIN
set #myReturn = 5;
return #myReturn;
END
When executing the stored proc in SQL Server, the returned value is '5'.
I copied your sproc and stepped through the SubSonic code and .Output is never set anywhere. A work around would be using an output parameter and referring to it after executing: sproc.OutputValues[0];
Here's a simple way to do it:
In the stored procedure, instead of using RETURN, use SELECT like this:
SELECT ##ROWCOUNT
or
SELECT #TheIntegerIWantToReturn
Then in the code use:
StoredProcName.ExecuteScalar()
This will return the single integer you SELECTED in your stored procedure.
CREATE PROCEDURE [dbo].[GetReturnValue]
#myVariable varchar(50)
#myReturn BIGINT OUTPUT
AS
declare #myReturn int
BEGIN
set #myReturn = 5;
return #myReturn;
END

Resources