Stored procedure from T-SQL in C# - c#

I create stored procedure in T-SQL
CREATE PROCEDURE price_proc #type_of_service int, #date_of_receipt date, #date_of_delivery date, #mechanic_id int, #car_id_p int, #price_for_work float
AS
DECLARE #count int, #car_id int
SELECT #car_id = car_id, #count = COUNT(car_id) FROM work WHERE car_id = #car_id_p GROUP BY car_id
IF(#count > 1 AND #count < 4 )
BEGIN
SET #price_for_work = #price_for_work - (#price_for_work * 0.1)
INSERT INTO work(type_of_service_id, date_of_receipt, date_of_delivery, mechanic_id, car_id, price_for_work) VALUES (#type_of_service, #date_of_receipt, #date_of_delivery, #mechanic_id, #car_id_p, #price_for_work)
END
ELSE IF(#count > 4)
BEGIN
SET #price_for_work = #price_for_work - (#price_for_work * 0.15)
INSERT INTO work(type_of_service_id, date_of_receipt, date_of_delivery, mechanic_id, car_id, price_for_work) VALUES (#type_of_service, #date_of_receipt, #date_of_delivery, #mechanic_id, #car_id_p, #price_for_work)
END
GO
I call it in my code
string d1 = String.Format("{0:yyyy-MM-dd}", dateTimePicker1.Value);
string d2 = String.Format("{0:yyyy-MM-dd}", dateTimePicker2.Value);
cmd = new SqlCommand("price_proc", SqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#type_of_service", SqlDbType.Int)).Value = type_of_service_id;
cmd.Parameters.Add(new SqlParameter("#date_of_receipt", SqlDbType.Date)).Value = d1;
cmd.Parameters.Add(new SqlParameter("#date_of_delivery", SqlDbType.Date)).Value = d2;
cmd.Parameters.Add(new SqlParameter("#mechanic_id", SqlDbType.Int)).Value = mechanic_id;
cmd.Parameters.Add(new SqlParameter("#car_id_p",SqlDbType.Int)).Value = car_id;
cmd.Parameters.Add(new SqlParameter("#price_for_work", SqlDbType.Float)).Value = price;
cmd.ExecuteNonQuery();
But it does not work? I print cmd.ExecuteNonQuery() and give -1. Help me please.

You either need to Select a result set, or return an integer from your stored procedure. By the looks of your code, I imagine you may wish to return the SCOPE_IDENTITY, which will equal the newly inserted ID.

Related

Get the primary key as output or return when you performing an Update query?

I'm trying to get the output parameter of primary key which is ID. When I do the update query I get Null. Can you please suggest a way to do this?
CREATE PROCEDURE sp_InsertTax
(#ID int output,
#TaxAuthorityID int,
#TaxClassificationID int,
#EntityID int,
#AppliesTo_TaxEntityTypeID int)
AS
IF EXISTS (SELECT * FROM Tax
WHERE TaxAuthorityID = #TaxAuthorityID
AND TaxClassificationID = #TaxClassificationID
AND EntityID = #EntityID
AND AppliesTo_TaxEntityTypeID = #AppliesTo_TaxEntityTypeID)
BEGIN
UPDATE Tax
SET TaxAuthorityID = #TaxAuthorityID,
TaxClassificationID = #TaxClassificationID,
EntityID = #EntityID,
AppliesTo_TaxEntityTypeID = #AppliesTo_TaxEntityTypeID
WHERE ID = #ID
END
ELSE
BEGIN
IF #ID IS NULL
BEGIN
INSERT INTO Tax(TaxAuthorityID, TaxClassificationID, EntityID, AppliesTo_TaxEntityTypeID)
VALUES (#TaxAuthorityID, #TaxClassificationID, #EntityID, #AppliesTo_TaxEntityTypeID)
SET #ID = Scope_Identity()
END
END
GO
The below is my ADO.NET code to call the update stored procedure:
public int InsertFederalTax(int ClassificID, int appliesTo)
{
int tax_id = 0;
Sqlconn.Open();
SqlCommand cmd = new SqlCommand("sp_InsertTax", Sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
var returnparameter = cmd.Parameters.AddWithValue("ID", SqlDbType.Int);
returnparameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#TaxAuthorityID", SqlDbType.Int).Value = 1;
cmd.Parameters.Add("#TaxClassificationID", SqlDbType.Int).Value = ClassificID;
cmd.Parameters.Add("#EntityID", SqlDbType.Int).Value = 0;
cmd.Parameters.Add("#AppliesTo_TaxEntityTypeID", SqlDbType.Int).Value = appliesTo;
cmd.ExecuteNonQuery();
if (!(returnparameter.Value is DBNull))
tax_id = Convert.ToInt32(returnparameter.Value);
Sqlconn.Close();
return tax_id;
}
I think you intended to capture the ID of an existing duplicate record, which you would do as follows. I've also added best practice template items for a SP. Also note the comment from marc_c about not prefixing your SP with sp_.
CREATE PROCEDURE InsertTax
(
#ID int output
, #TaxAuthorityID int
, #TaxClassificationID int
, #EntityID int
, #AppliesTo_TaxEntityTypeID int
)
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
-- This assumes that none of the parameters can ever be null
-- And from your comments we know that no duplicates can exist
SELECT #ID = ID
FROM Tax
WHERE TaxAuthorityID = #TaxAuthorityID
AND TaxClassificationID = #TaxClassificationID
AND EntityID = #EntityID
AND AppliesTo_TaxEntityTypeID = #AppliesTo_TaxEntityTypeID;
IF #ID IS NOT NULL BEGIN
UPDATE Tax
SET TaxAuthorityID = #TaxAuthorityID,
TaxClassificationID = #TaxClassificationID,
EntityID = #EntityID,
AppliesTo_TaxEntityTypeID = #AppliesTo_TaxEntityTypeID
WHERE ID = #ID;
END; ELSE BEGIN
INSERT INTO Tax (TaxAuthorityID, TaxClassificationID, EntityID, AppliesTo_TaxEntityTypeID)
VALUES (#TaxAuthorityID, #TaxClassificationID, #EntityID, #AppliesTo_TaxEntityTypeID);
SET #ID = SCOPE_IDENTITY();
END;
RETURN 0;
END;
GO
And I recommend declaring your return parameter as:
var returnparameter = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.InputOutput
};
cmd.Parameters.Add(returnparameter);
Please, may you try to change your C# code with this updates bellow, and give us feed-back:
public int InsertFederalTax(int ClassificID, int appliesTo)
{
int tax_id = 0;
Sqlconn.Open();
SqlCommand cmd = new SqlCommand("sp_InsertTax", Sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.Parameters["#ID"].Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#TaxAuthorityID", 1);
cmd.Parameters.AddWithValue("#TaxClassificationID", ClassificID);
cmd.Parameters.AddWithValue("#EntityID", 0);
cmd.Parameters.AddWithValue("#AppliesTo_TaxEntityTypeID", appliesTo);
cmd.ExecuteNonQuery();
if(!(cmd.Parameters["#ID"].Value is DBNull))
{
tax_id = Convert.ToInt32(cmd.Parameters["#ID"].Value);
}
Sqlconn.Close();
return tax_id;
}

How do I display the return value after execution of a stored procedure?

I am building a .NET Core 3.1 Web API that uses stored procedures.
One of the stored procedures takes input and select values from a form and returns a ticket once the form is submitted in the front end.
My SQL Server stored procedure that looks like this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CallSummaryAddO]
#SedonaUser NVarCHar(100),
#SystemID Int,
#ProblemID Int,
#ResolutionID Int,
#NextStepID Int,
#CustomerComments NVaRChar(1000),
#TechNotes NVaRChar(1000),
#CustomerOnCall NVarChar(200),
#CustomerCallBackPhone NVarChar(15)
AS
DECLARE #ServiceTicketID Int,
#CustomerID Int,
#CustomerSiteID Int,
#NextTechID Int,
#TicketStatus NVarCHar(10),
#Today DateTime,
#ClosedDate DateTime,
#ServiceLevel Int,
#Route Int,
#AutoNotify NVarChar(320)= '',
#CustomerBillID Int,
#ServiceCoordinator Int = 1,
#TicketNumber Int,
#TicketNumberAdded Int
EXEC Sandbox.dbo.Service_Ticket_Next #TicketNumber Output
SET #TicketNumberAdded = #TicketNumber
SET #TicketStatus = CASE WHEN #ResolutionID = 1 THEN 'OP' ELSE 'CL' END
SET #ClosedDate = CASE WHEN #ResolutionID = 1 THEN '1899-12-30' ELSE GETDATE() END
SELECT
#CustomerID = S.Customer_id,
#CustomerSiteID = S.Customer_Site_id,
#ServiceLevel = Service_Level_Id,
#Route = Route_Id,
#CustomerBillID = Ste.Customer_Bill_Id
FROM
Sandbox.dbo.ar_customer_system S
INNER JOIN
Sandbox.dbo.ar_customer_site ste ON ste.Customer_Site_Id = S.Customer_Site_Id
WHERE
Customer_System_Id = #SystemID
SET #Today = GETDATE()
SET #ServiceCoordinator = #NextStepID
INSERT INTO Sandbox.dbo.[SV_Service_Ticket]
([Ticket_Status],[Ticket_Number],[Customer_Id],[Customer_Site_Id],[Customer_System_Id]
,[Multiple_Systems],[Creation_Date],[Requested_By],[Requested_By_Phone],[Problem_Id]
,[Scheduled_For],[Last_Service_Tech_Id],[Estimated_Length],[Resolution_Id],[Billable]
,[Billed],[Equipment_Charge],[Labor_Charge],[Other_Charge],[TaxTotal],
[Regular_Hours],[Overtime_Hours],[Holiday_Hours],[Trip_Charge],[Invoice_Id],[Regular_Rate],[Overtime_Rate],[Holiday_Rate],[Bypass_Warranty],[Bypass_ServiceLevel],[IsInspection]
,[ClosedDate],[Manual_Labor],[Service_Company_Id],[Priority_Id],[Category_Id],[Expertise_Level]
,[Entered_By],[Invoice_Contact],[Signer],[Remittance],[Signature_Image],[Payment_Received]
,[Sub_Problem_Id],[Service_Level_Id],[UserCode],[Edit_Timestamp],[PO_Number],[CustomerComments],[Number_Of_Dispatches],[Route_Id]
,[Sub_Customer_Site_ID],[Customer_CC_Id],[Customer_Bank_Id],[Ticket_Status_Id],[Customer_EFT_Id],[Auto_Notify]
,[Customer_Bill_Id],[Customer_Contact_Id],[Requested_By_Phone_Ext] ,[Inspection_Id],[Service_Ticket_Group_Id]
,[Service_Coordinator_Employee_Id],[Resolved_Date],[Inspection_Incremented],[OPT_rowguid],[Bypass_TicketServiceCompany]
,[EntrySource])
VALUES
(#TicketStatus, #TicketNumber,#CustomerID, #CustomerSiteID, #SystemID,
'N', #Today, #CustomerOnCall, #CustomerCallBackPhone, #ProblemID,
'1899-12-30', 1, 60, #ResolutionID, 'N',
'', 0,0,0,0,
0,0,0,0,1,0,0,0,'N','N','N',
#ClosedDate,'N',56,2,2,3,
#SedonaUser,'','','N','0x4E6F205369676E6174757265204F6E2046696C65','N',
1,#ServiceLevel,#SedonaUser,#Today,'', #CustomerComments,0,#Route,
1,0,0,1,1,#AutoNotify,#CustomerBillID,1,'',1,1,#ServiceCoordinator,#ClosedDate,'N',NewID(),'N','Service')
SET #ServiceTicketID = ##IDENTITY
INSERT INTO Sandbox.dbo.SV_Service_Ticket_Notes (Service_Ticket_Id, Notes, Access_Level, UserCode, Entered_Date, Edit_UserCode, Edit_Date, Is_Resolution)
VALUES (#ServiceTicketID, #TechNotes,1,#SedonaUser, #Today, #SedonaUser, #Today, Case When #TicketStatus = 'CL' then 'Y' else 'N' end)
DECLARE #UserComments NVarChar(100)
SET #UserComments = 'Added Service Ticket ' + CONVERT(NVarChar,#TicketNumber)
INSERT INTO Sandbox.dbo.SY_Edit_Log (UserCode, Edit_Timestamp, TableName, Edit_Type_AUD, KeyField, KeyData, UserComments, SystemComments, Edit_Column_Name, OldData, NewData)
VALUES (#SedonaUser, #Today, 'SV_Service_Ticket', 'A', 'Ticket_Number', #TicketNumber, #UserComments, '','','','')
IF #TicketStatus = 'CL'
BEGIN
SET #UserComments = 'Closed Service Ticket ' + CONVERT(NVarChar,#TicketNumber)
INSERT INTO Sandbox.dbo.SY_Edit_Log (UserCode, Edit_Timestamp, TableName, Edit_Type_AUD, KeyField, KeyData, UserComments, SystemComments, Edit_Column_Name, OldData, NewData)
VALUES (#SedonaUser, #Today, 'SV_Service_Ticket', 'U', 'Ticket_Number', #TicketNumber, #UserComments, '','','','')
END
RETURN #TicketNumberAdded
My repository looks like this:
public async Task<CallSummaryAddResult> InsertCallSummaryAddResult(CallSummaryAddResult callSummaryAddResult)
{
using (SqlConnection sql = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.CallSummaryAddO", sql))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#SedonaUser", SqlDbType.NVarChar)).Value = callSummaryAddResult.SedonaUser;
cmd.Parameters.Add(new SqlParameter("#SystemID", callSummaryAddResult.SystemID));
cmd.Parameters.Add(new SqlParameter("#ProblemID", callSummaryAddResult.ProblemID));
cmd.Parameters.Add(new SqlParameter("#ResolutionID", callSummaryAddResult.ResolutionID));
cmd.Parameters.Add(new SqlParameter("#NextStepID", callSummaryAddResult.NextStepID));
cmd.Parameters.Add(new SqlParameter("#CustomerComments", SqlDbType.NVarChar)).Value = callSummaryAddResult.CustomerComments;
cmd.Parameters.Add(new SqlParameter("#TechNotes", SqlDbType.NVarChar)).Value = callSummaryAddResult.TechNotes;
cmd.Parameters.Add(new SqlParameter("#CustomerOnCall", SqlDbType.NVarChar)).Value = callSummaryAddResult.CustomerOnCall;
cmd.Parameters.Add(new SqlParameter("#CustomerCallBackPhone", SqlDbType.NVarChar)).Value = callSummaryAddResult.CustomerCallBackPhone;
//cmd.Parameters.Add(new SqlParameter("#TicketNumber", SqlDbType.Int));
//cmd.Parameters["#TicketNumber"].Direction = ParameterDirection.Output;
await sql.OpenAsync();
await cmd.ExecuteNonQueryAsync();
_callSummaryAddResults.Add(callSummaryAddResult);
return callSummaryAddResult;
}
}
}
When I execute this in SSMS, I am getting a new ticket number, but in code, I am only getting 0 back. I want to display the actual returned ticket number and not a 0 or 1 (success or failure).
My job is to return the TicketNumber and display this to the end-user once available. How can I make this happen?
Thanks in advance.

A subquery in SQL Server returned more than 1 value

I made a Stored Procedure in SQL SERVER. When I call the stored procedure in the c# application, the following error occurs: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, , >= or when the subquery is used as an expression
I don't understand why this error occurs, because I am returning 1 single INT value.
ALTER PROCEDURE [dbo].[spToevoegenUitslag]
#intPersoonID INT,
#intPersoonIDSnelsteRonde INT,
#intPersoonIDPolePosition INT,
#intGrandPrixID INT,
#intPuntenID INT,
#intSeizoenID INT,
#intID INT = NULL
AS
BEGIN
--Toevoegen punten van uitslag GrandPrix
SELECT #intID = COUNT(ID) + 1 FROM tblPuntenCoureur
INSERT INTO tblPuntenCoureur (ID, PersoonID, GrandPrixID, PuntenID, SeizoenID)
VALUES (#intID, #intPersoonID, #intGrandPrixID, #intPuntenID, #intSeizoenID)
--Toevoegen deelnemers van de GrandPrix
SELECT #intID = COUNT(ID) + 1 FROM tblGrandPrixPersoon
INSERT INTO tblGrandPrixPersoon (ID, GrandPrixID, PersoonID)
VALUES (#intID, #intGrandPrixID, #intPersoonID)
IF (SELECT ID FROM tblSnelsteRonde WHERE GrandPrixID = #intGrandPrixID AND SeizoenID = #intSeizoenID) IS NULL
BEGIN
SELECT #intID = COUNT(ID) + 1 FROM tblSnelsteRonde
INSERT INTO tblSnelsteRonde (ID, PersoonID, intPunt, GrandPrixID, SeizoenID)
VALUES (#intID, #intPersoonIDSnelsteRonde, 1, #intGrandPrixID, #intSeizoenID)
END
IF (SELECT ID FROM tblPolePosition WHERE GrandPrixID = #intGrandPrixID AND SeizoenID = #intSeizoenID) IS NULL
BEGIN
SELECT #intID = COUNT(ID) + 1 FROM tblPolePosition
INSERT INTO tblPolePosition (ID, PersoonID, GrandPrixID, SeizoenID)
VALUES (#intID, #intPersoonIDPolePosition, #intGrandPrixID, #intSeizoenID)
END
RETURN 1 --Toevoegen uitslag gelukt
END
c# code
using (SqlCommand cmd = new SqlCommand("spToevoegenUitslag", verbinding))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#intPersoonID", SqlDbType.Int).Value = PersoonID[0];
cmd.Parameters.Add("#intPersoonIDSnelsteRonde", SqlDbType.Int).Value = PersoonIDSnelsteRonde;
cmd.Parameters.Add("#intPersoonIDPolePosition", SqlDbType.Int).Value = PersoonIDPolePosition;
cmd.Parameters.Add("#intGrandPrixID", SqlDbType.Int).Value = GrandPrixID;
cmd.Parameters.Add("#intPuntenID", SqlDbType.Int).Value = PuntenID[0];
cmd.Parameters.Add("#intSeizoenID", SqlDbType.Int).Value = SeizoenID;
var returnParameter = cmd.Parameters.Add("#Return", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
verbinding.Open();
cmd.ExecuteNonQuery();
var result = returnParameter.Value;
int returnwaarde = int.Parse(string.Format("{0}", result));
Console.WriteLine(returnwaarde);
string title = "Resultaat";
string message = "";
if (returnwaarde == 1)
{
message = "Uitslag succesvol toegevoegd";
MessageBox.Show(message, title);
}
verbinding.Close();
(SELECT ID FROM tblSnelsteRonde WHERE GrandPrixID = #intGrandPrixID AND SeizoenID = #intSeizoenID) This query of yours might return more than one value if there is more than one row in the table with the given #intGrandPrixID and #intSeizoenID
You can try something Like (SELECT Count(ID) FROM tblSnelsteRonde WHERE GrandPrixID = #intGrandPrixID AND SeizoenID = #intSeizoenID) == 0. If this is what you intend to do

Building a dynamic where clause in a stored procedure command

I have a stored procedure where the arguments looks like this
Create Procedure [dbo].[myStoredProcedure]
#TaskId int = 0
, #FileName varchar(200) =''
, #DataDtFrom smalldatetime = '01/01/1900'
, #DataDtTo smalldatetime = '01/01/1900'
, #OFFSET INT = 0
, #FETCH INT = 2000
, #WhereClauseString varchar(5000) = ''
SELECT
DataDt
,EffDt
,LoanNumber
,UploadDate
,UploadedFileName
FROM dbo.myFileTable u
WHERE
(#DataDtTo = '01/01/1900' or DataDt between #DataDtFrom and #DataDtTo)
and (#TaskId = 0 or TaskId = #TaskId)
and (#FileName = '' or UploadedFileName like '%' + #FileName + '%')
**Where ??? = #WhereClauseString**
ORDER BY u.UploadDate
OFFSET #OFFSET ROWS
FETCH NEXT #FETCH ROWS ONLY
I initialize this in C#
var whereClauseString = "LoanNum in(111,222,444) and TaskId in (123,456,789)";
using (var conn = new MyEntities().Database.Connection)
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandTimeout = 1800;
cmd.CommandText = model.UploadStoredProcedure;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#TaskId", Convert.ToInt64(model.TaskId)));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#FileName", model.FileName ?? string.Empty));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#DataDtFrom", DateTime.Parse(model.adjFromDataDt.ToShortDateString()) <= DateTime.Parse(basicDate.ToShortDateString()) ? basicDate : model.adjFromDataDt.Date));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#DataDtTo", DateTime.Parse(model.adjToDataDt.ToShortDateString()) <= DateTime.Parse(basicDate.ToShortDateString()) ? basicDate : model.adjToDataDt.Date));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#OFFSET", model.Page));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#FETCH", model.PageSize));
**Dynamic Where clause** -->> System.Data.SqlClient.SqlParameter("#WhereClause", whereClauseString));
var da = new System.Data.SqlClient.SqlDataAdapter((System.Data.SqlClient.SqlCommand)cmd);
da.Fill(ds);
}
My question is it possible to build a dynamic where clause and pass it to the stored procedure and sort on the columns that are being referenced in the where clause?
How would I know which columns I need in the stored procedure that are being referenced in the where clause?
Would such a thing be possible with this stored Procedure and Entity Framework?
Anyway, if your DB is far from external attacks with SQL Injection you still can think in an easy solution based in Dinamic SQL, very often this way can solve quickly very complex problems otherwise:
CREATE Procedure [dbo].[myStoredProcedure]
#TaskId int = 0
, #FileName varchar(200) =''
, #DataDtFrom smalldatetime = '01/01/1900'
, #DataDtTo smalldatetime = '01/01/1900'
, #OFFSET INT = 0
, #FETCH INT = 2000
, #WhereClauseString varchar(5000) = ''
AS
BEGIN
DECLARE #SQL AS NVARCHAR(MAX);
SELECT #SQL = '
SELECT
DataDt
,EffDt
,LoanNumber
,UploadDate
,UploadedFileName
FROM dbo.myFileTable u
WHERE
('''+CONVERT(CHAR(10), #DataDtTo, 112)+''' = ''01/01/1900'' or DataDt between '''+CONVERT(CHAR(10), #DataDtFrom, 112)+''' and '''+CONVERT(CHAR(10), #DataDtTo, 112)+''')
and ('+CONVERT(CHAR(10), #TaskId)+' = 0 or TaskId = '+CONVERT(CHAR(10), #TaskId)+')
and ('+RTRIM(CONVERT(CHAR(100), #FileName))+' = '''' or UploadedFileName like ''%'+RTRIM(CONVERT(CHAR(100), #FileName))+'%'')
' +CONVERT(CHAR(100), #WhereClauseString)+'
ORDER BY u.UploadDate
OFFSET '+CONVERT(CHAR(10), #OFFSET)+' ROWS
FETCH NEXT '+CONVERT(CHAR(10), #FETCH)+' ROWS ONLY;
'
PRINT #SQL;
EXEC sp_ExecuteSQL #SQL;
END;

Stored procedure in SQL Server; syntax error

I have a stored procedure called SelFromWeather2 and I need to return values from table. When I perform syntax check I don't get errors, but when I call it from C# I get syntax error near SelFromWeather2.
Here is code:
CREATE PROCEDURE SelFromWeather2
#location VARCHAR(MAX),
#des VARCHAR(200) OUTPUT,
#min INT OUTPUT,
#max INT OUTPUT,
#humidity INT OUTPUT,
#pressure INT OUTPUT,
#speed INT OUTPUT,
#date Datetime OUTPUT
AS
IF EXISTS(SELECT * FROM Weather2 WHERE LOCATION LIKE #location)
BEGIN
CREATE TABLE T
(
forc XML,
loc VARCHAR(MAX),
dat Datetime
);
INSERT INTO T(forc, loc, dat) SELECT TOP 1 [FORECAST],[LOCATION],[DATE] FROM Weather2
WHERE LOCATION LIKE #location ORDER BY DATE DESC;
SET #location=(SELECT loc FROM T);
SET #location =(SELECT loc FROM T);
SET #des= (SELECT forc.value('(/Weather//Forecast/Description/node())[1]', 'nvarchar(max)') FROM T);
SET #min= (SELECT forc.value('(/Weather//Forecast/MinTemp/node())[1]', 'int') FROM T);
SET #max=(SELECT forc.value('(/Weather//Forecast/MaxTemp/node())[1]', 'int') FROM T);
SET #humidity=(SELECT forc.value('(/Weather//Forecast/Humidity/node())[1]', 'int') FROM T);
SET #pressure= (SELECT forc.value('(/Weather//Forecast/Pressure/node())[1]', 'int') FROM T);
SET #speed=(SELECT forc.value('(/Weather//Forecast/Speed/node())[1]', 'int') FROM T);
SET #date= (SELECT forc.value('(/Weather//Forecast/Date/node())[1]', 'Datetime') FROM T);
DROP TABLE T;
END
The code for calling this procedure is:
string location = "Paris";
SqlDataReader myReader = null;
SqlCommand myComand = new SqlCommand("SelFromWeather2", myConnection);
myComand.Parameters.AddWithValue("#location", location);
SqlParameter min = myComand.Parameters.Add("#min", System.Data.SqlDbType.Int);
SqlParameter max = myComand.Parameters.Add("#max", System.Data.SqlDbType.Int);
SqlParameter humidity = myComand.Parameters.Add("#humidity", System.Data.SqlDbType.Int);
SqlParameter pressure = myComand.Parameters.Add("#pressure", System.Data.SqlDbType.Int);
SqlParameter speed = myComand.Parameters.Add("#speed", System.Data.SqlDbType.Int);
SqlParameter dat = myComand.Parameters.Add("#date", System.Data.SqlDbType.DateTime);
SqlParameter des = myComand.Parameters.Add("#des", System.Data.SqlDbType.VarChar, 200);
min.Direction = System.Data.ParameterDirection.Output;
max.Direction = System.Data.ParameterDirection.Output;
humidity.Direction = System.Data.ParameterDirection.Output;
pressure.Direction = System.Data.ParameterDirection.Output;
speed.Direction = System.Data.ParameterDirection.Output;
dat.Direction = System.Data.ParameterDirection.Output;
des.Direction = System.Data.ParameterDirection.Output;
myComand.ExecuteReader();
int minTemp = (int)min.Value;
int maxTemp = (int)max.Value;
int hum = (int)humidity.Value;
int press = (int)pressure.Value;
int wind = (int)speed.Value;
string description = des.Value.ToString();
DateTime datum = (DateTime)dat.Value;
Please help, I'm stuck!
Set CommandType of myCommand to StoredProcedure
You need to set the CommandType to StoredProcedure
myCommand.CommandType = CommandType.StoredProcedure
The default is Text.

Categories

Resources