Stored procedure in SQL Server; syntax error - c#

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.

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 to call procedure in aspx.cs file to return true or false when record found in database

i wrote a procedure which return 1 and 0 which given below
CREATE PROCEDURE [dbo].[CheckPI]
#PI Varchar(50)
AS BEGIN
SET NOCOUNT ON;
DECLARE #Exists INT
IF EXISTS(SELECT * FROM Tbl_ILSM_Quotation WHERE QuotationNo = #PI)
BEGIN
SET #Exists = 1
END
ELSE
BEGIN
SET #Exists = 0
END
RETURN #Exists
// when i execute this code in sql then it gives right ans
DECLARE #ReturnValue INT
EXEC #ReturnValue = #ReturnValue
SELECT #ReturnValue
END
and aspx.cs file
protected string GetPI()
{
int customerId = GetCustomerID(); // customer id - 123
int year = Convert.ToInt32(ddlIdYear.SelectedValue);
string PI = "PI/" + year + "/" + customerId; // PI - PI/2017/123
//SqlDataReader myReader = null;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["JSSConnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("CheckPI", con);
cmd.Parameters.AddWithValue("#PI", PI);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter sqlParam = new SqlParameter("#ReturnValue", DbType.Boolean);
sqlParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(sqlParam);
cmd.ExecuteNonQuery();
//int retrnval = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
//Response.Write(cmd.Parameters["#ReturnValue"].Value);
return PI;
}
i made procedure to check that pi number is available or not in database if available then return 1 otherwise 0
then i call that SP in aspx.cs file but i am unable to check that what it return after execution 1 or 0
// Add an Out param to capture the return value from the Procedure
SqlParameter outParam = new SqlParameter();
outParam.SqlDbType = System.Data.SqlDbType.Int;
outParam.ParameterName = “#outParam”;
outParam.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outParam);
// Add an Out param to capture whether the Stored Proc executed correctly or not (exception)
SqlParameter retParam = new SqlParameter();
retParam.SqlDbType = System.Data.SqlDbType.Int;
retParam.ParameterName = “#retParam”;
retParam.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add(retParam);
// Execute the command
cmd.ExecuteNonQuery();
// Get the values
int retval = (int)cmd.Parameters[“#retParam”].Value;
int outval = (int)cmd.Parameters[“#outParam”].Value; // Should contain the value you've returned for existence of PI value
You've used INT to represent a boolean, you can change it to BIT within the Stored Proc to keep it consistent.
Instead of these lines:
SqlParameter sqlParam = new SqlParameter("#ReturnValue", DbType.Boolean);
sqlParam.Direction = ParameterDirection.Output;
use this:
SqlParameter sqlParam = new SqlParameter("#ReturnValue", DbType.Int32);
sqlParam.Direction = ParameterDirection.ReturnValue;
The value returned (with the RETURN statement) from the stored proc is always an integer, not a boolean (or string). So the type of the parameter needs to be changed. Plus you need the return value, as you didn't declare any output parameter, so you need a different direction.
Next you execute the query with
cmd.ExecuteNonQuery();
There is no select statement that returns values (everything after the RETURN in your stored proc is ignored), so this is enough.
After the execution, you can inspect the returned value:
int retVal = Convert.ToInt32(cmd.Parameters["#ReturnValue"].Value);
Then you can use that retVal variable, for instance by using return retVal == 1;. But then you need to change the return type of your method from string to bool.
i solved my problem. and answer is given below
Stored procedure
CREATE PROCEDURE [dbo].[CheckPI]
#PI Varchar(50),
#Exists INT = 0 out
AS BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM Tbl_ILSM_Quotation WHERE QuotationNo = #PI)
BEGIN
SET #Exists = 1
END
ELSE
BEGIN
SET #Exists = 0
END
and aspx.cs file code
protected string GetPI()
{
int customerId = GetCustomerID(); // customer id - 123
int year = Convert.ToInt32(ddlIdYear.SelectedValue);
string PI = "PI/" + year + "/" + customerId;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["JSSConnection"].ToString());
con.Open();
for (char i = 'A'; i <= 'Z'; i++)
{
PI = "PI/" + year + "/" + customerId + i; // PI - PI/2017/123
//SqlDataReader myReader = null;
SqlCommand cmd = new SqlCommand("CheckPI", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PI", PI);
SqlParameter outputParameter = new SqlParameter();
outputParameter.ParameterName = "#Exists";
outputParameter.SqlDbType = System.Data.SqlDbType.Int;
outputParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outputParameter);
cmd.ExecuteNonQuery();
int returnVal = Convert.ToInt32(outputParameter.Value.ToString());
if (returnVal == 1)
{
continue;
}
else
{
break;
}
}
//else
//{
// PI = "PI/" + year + "/" + customerId;
//}
con.Close();
//Response.Write(cmd.Parameters["#ReturnValue"].Value);
return PI;
}

Stored procedure from T-SQL in 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.

StoredProcedure In EntityFramework DateTime Error

In my project i have used EntityFramework 5 and I came up to use an SP in my Context. Like this
public virtual object GetEvaluations(int AgentId, DateTime StartDate, DateTime EndDate, int FormId)
{
DataTable table = new DataTable();
using (DbDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = _context.Database.Connection.CreateCommand();
adapter.SelectCommand.Parameters.Clear();
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.CommandText = "GetEvaluations";
SqlParameter aid = new SqlParameter("#AgentId", SqlDbType.Int);
aid.Value = AgentId;
SqlParameter sd = new SqlParameter("#StartDate", StartDate.Date.ToString("dd.MM.yyyy"));
SqlParameter ed = new SqlParameter("#EndDate", EndDate.Date.ToString("MM.dd.yyyy"));
SqlParameter fid = new SqlParameter("#FormId", SqlDbType.Int);
fid.Value = FormId;
adapter.SelectCommand.Parameters.Add(aid);
adapter.SelectCommand.Parameters.Add(sd);
adapter.SelectCommand.Parameters.Add(ed);
adapter.SelectCommand.Parameters.Add(fid);
adapter.Fill(table);
}
return table;
}
Here the DateTime formats different style but just working like this. Even this 2 parameters are looking to the same field in the table.
Please look at datetime formats (they are different) i think they must be same style.
My SP:
USE [EvaluationAssistt]
GO
/****** Object: StoredProcedure [dbo].[GetEvaluations] Script Date: 12.03.2015 11:25:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Hammit Yildirim
-- Create date: 11.03.2015
-- Description: Defined for Category Point Reports Performance
-- =============================================
ALTER PROCEDURE [dbo].[GetEvaluations]-- 258,'1.11.2014','11.24.2014',8
#AgentId int,
#StartDate Datetime,
#EndDate Datetime,
#FormId int
AS
BEGIN
SET NOCOUNT ON;
select fce.Id from FormsCallsEvaluated fce
left join FormsCalls fc on fce.CallId = fc.CallId
where fc.AgentId=#AgentId and fc.DateStarted > #StartDate and fc.DateStarted < #EndDate and fce.FormId=#FormId
END
What is my problem
I tryed below and returning me empty table
public virtual object GetEvaluations(int AgentId, DateTime StartDate, DateTime EndDate, int FormId)
{
DataTable table = new DataTable();
using (DbDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = _context.Database.Connection.CreateCommand();
adapter.SelectCommand.Parameters.Clear();
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.CommandText = "GetEvaluations";
SqlParameter aid = new SqlParameter("#AgentId", SqlDbType.Int);
aid.SqlValue = AgentId;
SqlParameter sd = new SqlParameter("#StartDate", SqlDbType.DateTime);
sd.SqlValue = StartDate.Date;
SqlParameter ed = new SqlParameter("#EndDate", SqlDbType.DateTime);
ed.SqlValue = EndDate.Date;
SqlParameter fid = new SqlParameter("#FormId", SqlDbType.Int);
fid.SqlValue = FormId;
adapter.SelectCommand.Parameters.Add(aid);
adapter.SelectCommand.Parameters.Add(sd);
adapter.SelectCommand.Parameters.Add(ed);
adapter.SelectCommand.Parameters.Add(fid);
adapter.Fill(table);
}
return table;
}
It is working SQL side just like this
USE [EvaluationAssistt]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[GetEvaluations]
#AgentId = 258,
#StartDate = N'1.11.2014',
#EndDate = N'11.24.2014',
#FormId = 8
SELECT 'Return Value' = #return_value
GO
You defined your #StartDate and #EndDate columns as DateTime but you try to pass them string values.
Just pass the right type and values to your parameter like;
SqlParameter sd = new SqlParameter("#StartDate", StartDate.Date);
SqlParameter ed = new SqlParameter("#EndDate", EndDate.Date);

Calling one stored procedure from another in C#

I have error 'Error converting data type nvarchar to decimal'
when call stored procedure call another stored procedure from C# as
cmd = new SqlCommand("tax_Base_emp", con);
cmd.CommandType = CommandType.StoredProcedure;
parm1 = new SqlParameter("#emp_code", SqlDbType.BigInt);
parm1.Value = emp_code;
parm1.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm1);
parm2 = new SqlParameter("#co_id", SqlDbType.BigInt);
parm2.Value = Settings.Default.comp_id;
parm2.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm2);
parm3 = new SqlParameter("#d", SqlDbType.DateTime);
parm3.Value = Convert.ToDateTime("31/1/2010");
parm3.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm3);
parm4 = new SqlParameter("#y", SqlDbType.Int);
parm4.Value =int.Parse(textBox2.Text);
parm4.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm4);
parm5 = new SqlParameter("#check_month", SqlDbType.Int);
parm5.Value =1;
parm5.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm5);
parm6 = new SqlParameter("#month", SqlDbType.Int);
parm6.Value =8;
parm6.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm6);
SqlParameter parm7 = new SqlParameter("#indate", SqlDbType.DateTime);
parm7.Value = Convert.ToDateTime("8/5/2010");
parm7.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm7);
SqlParameter parm8 = new SqlParameter("#Sumtotal", SqlDbType.Decimal);
parm8.Scale = 2;
parm8.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parm8);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
decimal tax_value = Convert.ToDecimal(cmd.Parameters["#Sumtotal"].Value);
And the stored proecdure called:
ALTER PROCEDURE Tax_Base_emp
#emp_code bigint,
#co_id bigint,
#d datetime,
#y int,
#check_month int,
#month int,
#indate datetime,
#Sumtotal decimal(8,2) output
AS
declare #tax_main_sal decimal(8,2)
declare #tax_var_sal decimal(8,2)
declare #salary decimal(8,2)
declare #insh_varsalary decimal(8,2)
declare #insh_value decimal(8,2)
declare #vacation_value decimal(8,2)
declare #vacation_varsalary decimal(8,2)
declare #ded_value decimal(8,2)
declare #ben_value decimal(8,2)
exec Taxable_mainsalary #emp_code,#co_id,#tax_main_sal output
exec taxable_varsalary #emp_code,#co_id, #tax_var_sal output
----taxableSalary---------------
set #salary=#tax_main_sal+#tax_var_sal
----insurance-------------------
exec varsalary_insh #emp_code,#co_id,#d,#y, #insh_varsalary output
exec insh_no #emp_code,#co_id,#insh_varsalary,#check_month, #insh_value output
----vacation--------------------
exec vacation_varsalary #emp_code,#co_id,#vacation_varsalary output
exec vacation_value #emp_code,#co_id,#y,#month,#vacation_varsalary,output
---------deduction---------------
exec deduction_for_tax #emp_code,#co_id,#indate,#ded_value output
-------------benifit------------
exec benfit_for_tax #emp_code,#co_id,#indate,#ben_value output
-----------------------------------NetSalary--------------------------------------------------------
set #Sumtotal=(isnull(#salary,0)+isnull(#ben_value,0))-(isnull(#insh_value,0)+isnull(#vacation_value,0)+isnull(#ded_value,0))
return
I don't see anything wrong with your C# code - it's really hard to tell what would be causing the problem. Your C# code is just simply calling a single stored proc - that shouldn't be a problem, really.
However, I do have a few recommendations for your coding style:
put your SqlConnection and SqlCommand into using(....) { .... } blocks to make your code more reliable
try to avoid specifying default property values, like Direction = ParameterDirection.Input; over and over again; the .Input is the default - only specify it when you deviate from that default
if you do the same steps over and over and over again - why don't you put this in a method and call that method a couple of times?? This also saves you from having to create a gazillion of SqlParameter objects that you then just throw away .....
You'd end up with something like:
public void CallStoredProc()
{
using(SqlConnection con = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand("tax_Base_emp", con))
{
cmd.CommandType = CommandType.StoredProcedure;
AddParameter(cmd.Parameters, "#emp_code", SqlDbType.BigInt, emp_code);
AddParameter(cmd.Parameters, "#co_id", SqlDbType.BigInt, comp_id);
AddParameter(cmd.Parameters, "#d", SqlDbType.DateTime, Convert.ToDateTime("31/1/2010"));
AddParameter(cmd.Parameters, "#y", SqlDbType.Int, int.Parse(textBox2.Text));
AddParameter(cmd.Parameters, "#check_month", SqlDbType.Int, 1);
AddParameter(cmd.Parameters, "#month", SqlDbType.Int, 8);
AddParameter(cmd.Parameters, "#indate", SqlDbType.DateTime, Convert.ToDateTime("8/5/2010"));
AddOutputParameter(cmd.Parameters, "#Sumtotal", SqlDbType.Decimal, 8, 2);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
decimal tax_value = Convert.ToDecimal(cmd.Parameters["#Sumtotal"].Value);
}
}
public void AddParameter(SqlParameterCollection params, string name, SqlDbType type, object value)
{
SqlParameter tmpParam = new SqlParameter(name, type);
tmpParam.Value = value;
params.Add(tmpParam);
}
public void AddOutputParameter(SqlParameterCollection params, string name, SqlDbType type, int precision, int scale)
{
SqlParameter tmpParam = new SqlParameter(name, type);
tmpParam.ParameterDirection = Direction.Output;
tmpParam.Precision = precision;
tmpParam.Scale = scale;
params.Add(tmpParam);
}
I can't see anything in the code you have posted that would cause that.
I suspect that the error is in one of the 8 stored procedures you are calling where you are assigning an nvarchar to a decimal.
I'd comment these all out temporarily and just return a dummy number if that fixes it uncomment half and try again. If the error reoccurs then you know it is in one of the ones you just uncommented. i.e. do a binary search to find the offending procedure.

Categories

Resources