Why is SQL Server converting my decimal parameter 12.50 to 12.49999999 - stored-procedures

I am passing a decimal value from C# to a SQL Server stored procedure.
The parameter in the stored procedure is defined as #latitude decimal. Right before going into the stored procedure, the value is 25.631230
When running the profiler I can see that SQL Server sees the value as: 25.631229999999999
This is obviously a much different value when you are dealing with longitude/latitude.
SqlParameter lat = new SqlParameter { SqlDbType = System.Data.SqlDbType.Decimal, Value = 25.631230, ParameterName = "#latitude" };
cmd.Parameters.Add(lat);
cmd.CommandText = storedProcName;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.ExecuteReader()
Hope it's just a setting somewhere ;)

Adding the precision in the stored procedure "decimal(18, 15)" was the correct solution. After I did that another error popped up that was confusing me but turns out it was unrelated to this specific question.
Thanks all that pointed me in the right direction.

Related

Calling Oracle 11g Stored Procedure Using VB6

I have a simple Oracle procedure as below. I am trying to call the procedure using VB6 and extract the output from the procedure.
CREATE OR REPLACE PROCEDURE EXTRACTTXN (reportdate IN DATE, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT
TXN_ID,
TXN_ACTION,
TXN_STATUS,
TXN_DATE,
TXN_AMOUNT
FROM TRANSACTIONS
WHERE
TRUNC(TXN_DATE) = TRUNC(reportdate)
END EXTRACTTXN;
The VB Code goes like this;
Sub FetchTransactions(ByVal ReportDate As Date, cnnMine as ADODB.Connection)
On Error GoTo TrapErr
Dim cmdMine As ADODB.Command, rsMine As ADODB.Recordset
cmdMine.ActiveConnection = cnnMine
cmdMine.CommandTimeout = 300
cmdMine.CommandType = adCmdStoredProc
cmdMine.CommandText = "EXTRACTTXN"
cmdMine.Parameters.Append cmdMine.CreateParameter("reportdate", adDate, adParamInput, , Format(ReportDate, "DD-MMM-YYYY"))
cmdMine.Parameters.Append cmdMine.CreateParameter("p_recordset", adVariant, adParamOutput)
Set rsMine = cmdMine.Execute
Do While rsMine.EOF
Debug.Print rsMine!TXN_ID, rsMine!TXN_ACTION, rsMine!TXN_STATUS, rsMine!TXN_DATE, rsMine!TXN_AMOUNT
rsMine.MoveNext
Loop
rsMine.Close
Exit Sub
TrapErr:
MsgBox Err.Number & " - " & Err.Description, vbExclamation, App.ProductName
End Sub
While running the code, I get the following Error:
ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'EXTRACTTXN'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Anything wrong in my code? Appreciate help.
Niz
The problem is that the types of your arguments as specified in your VB code don't match the types of the arguments as specified in your PL/SQL code. The most likely reason for your problem is that the Format function in VB6 returns a Variant type, not a Date type, and that Variant type is set to be a String type. See this for more information on the Format function.
In case you don't know, the way that Variant variables are set up is that they reserve 8 bytes to tell the world what the actual variable type is. So, if you pass your ReportDate in after applying the Format function to it, it will be a Variant that's telling the world it's a string. It's possible that the ADO Parameter object is happy with that (SQL Server is happy to parse properly-formatted strings into Date fields, after all) and Oracle isn't. In my limited experience with Oracle, I've found that it's fussier about that sort of thing than SQL Server.
Try losing the Format function and see if you at least get a different error.
I have managed to get this sorted. It's mainly due to me being new to Oracle and its complexity.
Here are the changes I made;
Stored Procedure Changes. Note that I have changed TRUNC(reportdate, 'DD') on the Where clause.
CREATE OR REPLACE PROCEDURE EXTRACTTXN (reportdate IN DATE, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT
TXN_ID,
TXN_ACTION,
TXN_STATUS,
TXN_DATE,
TXN_AMOUNT
FROM TRANSACTIONS
WHERE
TRUNC(TXN_DATE) = TRUNC(reportdate, 'DD')
END EXTRACTTXN;
VB Code Changes (Note that I have change the CommandText within parenthesis with a Call, removed the parameter name, changed the date format to DD/MMM/YYYY and removed the output parameter)
Sub FetchTransactions(ByVal ReportDate As Date, cnnMine as ADODB.Connection)
On Error GoTo TrapErr
Dim cmdMine As ADODB.Command, rsMine As ADODB.Recordset
cmdMine.ActiveConnection = cnnMine
cmdMine.CommandTimeout = 300
cmdMine.CommandType = adCmdStoredProc
cmdMine.CommandText = "{ call EXTRACTTXN}"
cmdMine.Parameters.Append cmdMine.CreateParameter(, adDate, adParamInput, , Format(ReportDate, "DD/MMM/YYYY"))
Set rsMine = cmdMine.Execute
Do While rsMine.EOF
Debug.Print rsMine!TXN_ID, rsMine!TXN_ACTION, rsMine!TXN_STATUS, rsMine!TXN_DATE, rsMine!TXN_AMOUNT
rsMine.MoveNext
Loop
rsMine.Close
Exit Sub
TrapErr:
MsgBox Err.Number & " - " & Err.Description, vbExclamation, App.ProductName
End Sub
The above worked perfectly.
Regards, Niz

SSIS Script Component Call Stored Procedure returns -1

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

How to use Slickgrid Formatters with MVC

I am working on a first Slickgrid MVC application where the column definition and format is to be stored in a database. I can retrieve the list of columns quite happily and populate them until I ran into the issue with formatting of dates. No problem - for each date (or time) column I can store a formatter name in the database so this can be retrieved as well. I'm using the following code which works ok:
CLOP_ViewColumnsDataContext columnDB = new CLOP_ViewColumnsDataContext();
var results = from u in columnDB.CLOP_VIEW_COLUMNs
select u;
List<dynColumns> newColumns = new List<dynColumns>();
foreach(CLOP_VIEW_COLUMN column in results)
{
newColumns.Add(new dynColumns
{
id = column.COLUMN_NUMBER.ToString(),
name = column.HEADING.Trim(),
field = column.VIEW_FIELD.Trim(),
width = column.WIDTH,
formatter = column.FORMATTER.Trim()
});
}
var gridColumns = new JavaScriptSerializer().Serialize(newColumns);
This is all fine apart from the fomatter. An example of the variable gridColumns is:
[{"id":"1","name":"Date","field":"SCHEDULED_DATE","width":100,"formatter":"Slick.Formatters.Date"},{"id":"2","name":"Carrier","field":"CARRIER","width":50,"formatter":null}]
Which doesn't look too bad however the application the fails with the error Microsoft JScript runtime error: Function expected in the slick.grid.js script
Any help much appreciated - even if there is a better way of doing this!
You are assigning a string to the formatter property, wich is expected to be function.
Try:
window["Slick"]["Formatters"]["Date"];
But i really think you should reconsider doing it this way and instead store your values in the db and define your columns through code.
It will be easier to maintain and is less error prone.
What if you decide to use custom editors and formatters, which you later rename?
Then your code will break or you'll have to rename all entries in the db as well as in code.

What's wrong in Classic ASP StoredProcedure insert statement

Here is the classic ASP code
Set objCommandSec = CreateObject("ADODB.Command")
With objCommandSec
Set .ActiveConnection = MyConn
.CommandType = adCmdStoredProc
.CommandText = "ReportsPDFInsert"
.CreateParameter "#StatsID", adInteger, adParamInput
.Parameters("#StatsID") = xStats_ID
.CreateParameter "#MemberID", adInteger, adParamInput
.Parameters("#MemberID") = xMemberID
.CreateParameter "#LanguageID", adInteger, adParamInput
.Parameters("#LanguageID") = 1 '1=EN
.CreateParameter "#PDFFilename", adVarWChar , adParamInput
.Parameters("#PDFFilename") = PDFFilename
.Execute
End With
Here is the stored procedure code
ALTER PROCEDURE [dbo].[ReportsPDFInsert]
-- Add the parameters for the stored procedure here
#StatsID INT
,#MemberID INT
,#LanguageID INT
,#PDFFilename NVARCHAR(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO [dbo].[ReportsPDF]
([StatsID]
,MemberID
,[LanguageID]
,[PDFFilename]
,[DateCreated])
VALUES
(#StatsID
,#MemberID
,#LanguageID
,#PDFFilename
,GETDATE())
END
I get error as
Error number: -2147217904
Error description: Procedure 'ReportsPDFInsert' expects parameter '#StatsID', which was not supplied.
Source: Microsoft OLE DB Provider for SQL Server
If I execute the stored procedure itself, then it is working fine. I have similar classic asp code in other page, and that works fine as well. yes, I made sure xStats_ID does have value. I printed just before the .Execute and I see the value.
Please somebody shed some light. Thanks
Try appending the parameters explicitly using something like this:
cmd.Parameters.Append cmd.CreateParameter("#StatsID",adInteger, adParamInput,xStats_ID)
instead of .Parameters("")
Here is another post that might help:
How to make a parametrized SQL Query on Classic ASP?
Only today I figured what was the problem.
I haven't included the adovbs.inc file for the constants to work.
And I don't know why it was throwing some other error message.
good reason to move away from Classic ASP [only if my boss listens]
Try dropping the "#" in your parameter names.

Converting call to a stored procedure from C# to VB.net

Dim sql1 As String = ("EXEC [dbo].[usp_GetReportData_All] #ReportID=N'{0}', #StartDate=N'{1}' #EndDate=N'{2}', #StartDate2=N'{3}' #EndDate2=N'{4}'", repotid1, startdata1, EndDate1, StartDate3,Enddate3 ) (this is what I tried to do in VB.net)
Ok normally I have this line of code in C# saved into a string then from there I use that string to run the stored procedure into a datatable. Apparently vb.net doesn't seem to like that format so I'm just wondering if it is possible to save this line into a string or not in vb.net
Oops mistake, this is what I do in C#:
string srcSQL = string.Format(then the line in parans up there)
As you can see in this examples of Console.Writeline(http://msdn.microsoft.com/en-us/library/aa324760(v=vs.71).aspx), you can use it for example:
Console.WriteLine("Grand total:\t{0,8:c}", Total);
For Example
Dim total As String
Dim result As String
total = "1000"
result = String.Format("restulado {0}", total)
MsgBox(result)
The var Total is formatted as currency
use String.Format("YourSQLText", parameter0, parameter1)

Resources