How to call ProgresSql stored procedure with timestamp parameters - c#

I have a very simple stored procedure which I'm trying to execute in c#
CREATE OR REPLACE PROCEDURE get_documents(
p_issue_date TIMESTAMP
)
language plpgsql
as $$
begin
select * from documents ;
end; $$;
Repository.cs
var test2 = await _dbContext.QueryAsync<Documents>("get_documents", new
{
p_issue_date = input.Date //This is a DateTime object
}, isStoredProcedure: true);
I get the error message No procedure matches the given name and argument types The parameter incoming is timestamp with time zone instead of timestamp without timezone. May I ask how do I execute sproc with timezone without parameters passed.

Related

String was not recognized as a valid DateTime, stored procedure empty parameter

I wrote a stored procedure in SQL Server. I have a parameter of type smalldatetime. I want to send this parameter blank when I run it with LINQ. When I want to send it, I get this error.
String was not recognized as a valid DateTime.
How can I send the date format blank?
C#, LINQ;
var query = ctx.onayListele(Convert.ToDateTime(dataList.olusturulmaTarihi)).ToList();
SQL:
ALTER PROCEDURE [dbo].[onayListele]
#in_olusturmaTarihi smalldatetime = NULL
AS
BEGIN
SELECT
Onay.onayID, alep.olusturulmaTarihi, TalepTuru.talepTuruAdi,
TalepDurumu.talepDurumuAciklamasi
FROM
Onay
WHERE
(#var_olusturmaTarihi IS NULL OR
CONVERT(DATE, Talep.olusturulmaTarihi) = CONVERT(DATE, #var_olusturmaTarihi))
END
At first, I thought you needed to change your stored procedure.
Now that I've read the question again, I've realized that the error message comes from the c# side, not from the stored procedure (that I still think you should change).
Attempting to convert a null or empty string to DateTime will result with the error in your question. To avoid that, you need to make sure the string can in fact be converted to DateTime before sending it to the stored procedure:
DateTime datetime;
DateTime? olusturulmaTarihi = null;
if(DateTime.TryParse(dataList.olusturulmaTarihi, out datetime))
{
olusturulmaTarihi = (DateTime?)datetime;
}
var query = ctx.onayListele(olusturulmaTarihi).ToList();
This way, you will send null to the stored procedure if the string can't be parsed as DateTime, and avoid the error.
As to the stored procedure, I would suggest writing it like this instead:
ALTER PROCEDURE [dbo].[onayListele]
#in_olusturmaTarihi date = NULL
AS
BEGIN
SELECT Onay.onayID,
alep.olusturulmaTarihi,
TalepTuru.talepTuruAdi,
TalepDurumu.talepDurumuAciklamasi
FROM Onay
WHERE #var_olusturmaTarihi IS NULL
OR CONVERT(date,Talep.olusturulmaTarihi) = #var_olusturmaTarihi
END
Please note that if you have an index on Talep.olusturulmaTarihi, this stored procedure will not be able to use it. In that case, you better use something like this instead:
ALTER PROCEDURE [dbo].[onayListele]
#in_olusturmaTarihi date = NULL
AS
BEGIN
SELECT Onay.onayID,
alep.olusturulmaTarihi,
TalepTuru.talepTuruAdi,
TalepDurumu.talepDurumuAciklamasi
FROM Onay
WHERE #var_olusturmaTarihi IS NULL
OR
(
Talep.olusturulmaTarihi >= CAST(#var_olusturmaTarihi as datetime) -- or whatever the data type of the column is
AND Talep.olusturulmaTarihi < DATEADD(DAY, 1, CAST(#var_olusturmaTarihi as datetime)) -- or whatever the data type of the column is
)
END

EF6 stored procedure must declare scalar variable

I am trying to call a stored procedure using C# EF6 to bring back data. I have tried to run the stored procedure in SQL management studio and it seems to work fine, however when I try to run it in my application I get an error saying "Must declare the scalar variable "#devID"
Here is part of my method in my application calling the stored procedure
public IHttpActionResult GetMetrics(int deviceID, string attribute, string startDate)
{
if (deviceID == 0)
{
return NotFound();
}
var metrics = db.Database.SqlQuery<Metrics>("GetMetrics #devID, #MetricType, #startTime", deviceID, attribute, startDate).ToList();
and here is my stored procedure:
ALTER PROCEDURE [dbo].[GetMetrics]
-- Add the parameters for the stored procedure here
#devID int,
#MetricType nvarchar(20),
#startTime 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
SELECT *
FROM dbMetrics
WHERE deviceID = #devID and MetricType = #MetricType and timeStamp >= #startTime
ORDER BY timeStamp
END
As per the documentation, if you want to use named parameters, you need to pass SqlParameter objects like this:
var metrics = db.Database.SqlQuery<Metrics>("GetMetrics #devID, #MetricType, #startTime",
new SqlParameter("devID", deviceID),
new SqlParameter("MetricType", attribute),
new SqlParameter("startTime", startDate)
).ToList();

How to take input from SQL stored procedure to a return statement

alter procedure [dbo].[XXX]
(
#vendorworksationID uniqueidentifier ,
#sdate date,
#edate date,
#total int out
)
begin
select #total = COUNT(*)
from AdvertisedCampaignHistory a
where
CAST(a.CreationDate AS DATE) BETWEEN CAST(#sdate as DATE) AND CAST(#edate as DATE)
and a.CampaignID in (select cc.BCampaignID
from BeaconCampaign cc, VendorWorkStation vw
where cc.VendorWorkStationID = vw.VendorWorkStationID
and VendorID = #vendorworksationID)
return #total
end
The above code shows the stored procedure that return an integer value from SQL Server
ObjectParameter Output = new ObjectParameter("total", typeof(Int32));
var resBC = this.Context.getTotalSentBeaconCampaign(VendorWorkstationID, sdate,edate,Output).FirstOrDefault();
The above code shows how I am passing parameters and retrieving the value on the C# side
While running the code I am getting following error
The data reader returned by the store data provider does not have
enough columns for the query requested.
What could be the possible cause for this error?
Entity Framework cannot support Stored Procedure Return scalar values out of the box.To get this to work with Entity Framework, you need to use "Select" instead of "Return" to return back the value.
More Ref : http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values

Parameter does not exist as a stored procedure parameter

ALTER PROCEDURE [dbo].[SelectCompletionNonCompletionCourseReport]
#LearnerName NVARCHAR(510) = NULL,
#ManagerId INT = NULL,
#CourseId INT = NULL,
#StartDateFrom SMALLDATETIME = NULL,
#StartDateTo SMALLDATETIME = NULL,
#TeamList XML = NULL,
#JobID NVARCHAR(max)=NULL,
#CourseStatus NVARCHAR(20)=NULL,
#ReportAdminID INT=0,
#ReportTeamList NVARCHAR(max)=NULL,
#RowsTotal int = 0,
#PageIndex int = 1,
#RowsPerPage int = 10
AS
BEGIN
DECLARE #TblCrieiria TABLE
(
id INT IDENTITY(1, 1),
areacode NVARCHAR(11),
regioncode NVARCHAR(11),
teamcode NVARCHAR(11)
)
IF #TeamList IS NULL
BEGIN
INSERT INTO #TblCrieiria VALUES(NULL,NULL,NULL)
END
BEGIN
This is the beginning of the procedure...
using (Database db = new Database(DScape.DAL.Config.ConfignPropertyName.DSCAPELMS_CONNECTION_STRING_NAME))
{
var cmd = new SqlCommand
{
CommandText = "SelectCompletionNonCompletionCourseReport",
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#LearnerName", LearnerName);
cmd.Parameters.AddWithValue("#ManagerId", ManagerId);
cmd.Parameters.AddWithValue("#CourseId", CourseId);
cmd.Parameters.AddWithValue("#StartDateFrom", StartDateFrom);
cmd.Parameters.AddWithValue("#StartDateTo", StartDateTo);
cmd.Parameters.AddWithValue("#TeamList", TeamList);
cmd.Parameters.AddWithValue("#JobID", JobID);
cmd.Parameters.AddWithValue("#CourseStatus", CourseStatus);
cmd.Parameters.AddWithValue("#ReportAdminID", ReportAdminID);
cmd.Parameters.AddWithValue("#ReportTeamList", ReportTeamList);
cmd.Parameters.AddWithValue("#PageIndex", 1);
DataSet dsClient = db.GetDataSet(cmd);
if (dsClient.Tables.Count > 0)
return dsClient.Tables[0];
else
return null;
}
This is the method which communicates with the procedure, and it gaves me an error
Parameter does not exist as a stored procedure parameter/ function/procedure take too many arguments...
It's about #PageIndex parameter. Doesn't matter what is the value, we don't talk for values here but for parameter which is defined in the stored procedure but doesn't work?
And for the record, this problem did pop-up today w/o any code writing/modifying just appeared as I tried to do that report, when yesterday it was all good...I have a teammate which is next to me with absolute the same code both in sql and c# and it works just fine on his pc, but mine throws this errors, I'm trying to resolve this from 3 hours and I am completely out of answers , so please give me direction in which should I continue to resolve this .....................
and I say again, the problem is not from the connection to DB or type of the parameter or the value, the error is committed with the parameter itself - does not exist in the procedure, which is insane in my opinion.
Given that all parameters are optional, you are not required to explicitly provide any of them from your client code. Default values will be provided for you by SQL Server. The contract explictly states it in the stored procedure's signature.
An optional parameter is exactly that: optional. If you had provided the incorrect number of parameters, SQL Server would have returned a different error, indicating that the number of parameters was incorrect. This is not the case. Instead, you are seeing that you are asking for a parameter that is undefined, which indicates that the stored procedure signature you think you are calling does not match the stored procedure signature you are actually calling.
Verify that you are both connecting to the same database instance. If you are not, verify that the stored procedure is identical on both database instances.
parameter count doesnt match. check the params again.
You have to send parameters for rowstotal and rowsperpage as well because you have declared them at the top before "begin" clause.
If you do not want to send that params and they will be just constant, please declare them below as variable or constant, not a parameter.
i.e.
CREATE PROCEDURE DeleteById
#TableName sysname,
#Id int
AS
BEGIN
DECLARE #StrId AS VARCHAR(50)
SET #StrId = CONVERT(VARCHAR(50), #Id)
--any sp code here
END
Hope this helps.

How to call a stored procedure from MVC that requires datetimes

I'm wanting to call this stored procedure with input parameters:
proc [dbo].[Invoice_GetHomePageInvoices] (
#FinancialYearStartDate datetime = null
, #FinancialYearEndDate datetime = null
Trouble with this is the way I usually call a stored proc from my code is:
return _db.Database.SqlQuery<HomePageInvoice>(string.Format("EXEC Invoice_GetHomePageInvoices #FinancialYearStartDate = '{0}', #FinancialYearEndDate = '{1}'", financialYear.StartDate.ToString(), financialYear.EndDate.ToString()));
So this isn't going to work because I've basically converted my datetimes to strings.
How the heck am I supposed to do this?
You should use sql parameters, basically like this:
var startDate = new SqlParameter("FinancialYearStartDate", dateTimeValueHere);
var endDate = new SqlParameter("FinancialYearEndDate", dateTimeValueHere);
return _db.Database.SqlQuery<HomePageInvoice>("Invoice_GetHomePageInvoices", startDate, endDate);
More info: How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5
convert the date to a string with specific format.
use SQL code to convert it back to an sql datetime object.
When using sql server (microsoft):
http://msdn.microsoft.com/en-us/library/ms187928.aspx
"convert(datetime, '{0}', 103)", financialYear.EndDate.ToString("MM/dd/yyyy")
edit: Ropstah's method is actually better, this is just the way I used to do it :P

Categories