Getting weird value in C# - c#

Getting exactly correct data in stored procedure. but when i am trying to get that value in C# datatable getting wrong data. not sure why i am getting that.
Here is my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetSurveyStatistic]
(#SurveyID int,
#NameOfSubmitter varchar(200),
#NameOfPrivacyContact varchar(200),
#HspOrganizationalName varchar(200),
#HspSiteNumber varchar(200),
#FromDate datetime,
#ToDate datetime,
#weekly bit)
AS
BEGIN
IF (#ToDate IS NOT NULL)
SET #ToDate = DATEADD(DAY, 1, #ToDate)
IF #Weekly = 0
BEGIN
SELECT
CAST(CAST(StartedDateTime AS date) AS varchar(10)) Value,
COUNT(*) cnt
FROM
SubmittedSurveys
WHERE
(SurveyID = #SurveyID OR #SurveyID IS NULL)
AND (StartedDateTime >= #FromDate OR #FromDate IS NULL)
AND (StartedDateTime <= #ToDate OR #ToDate IS NULL)
AND (LOWER(ProvidedNameOfSubmitter) LIKE LOWER(#NameOfSubmitter) + '%'
OR #NameOfSubmitter IS NULL OR #NameOfSubmitter = '')
AND (LOWER(NameOfPrivacyContact) LIKE LOWER(#NameOfPrivacyContact) + '%'
OR #NameOfPrivacyContact IS NULL
OR #NameOfPrivacyContact = '')
AND (LOWER(HspOrganizationalName) LIKE LOWER(#HspOrganizationalName) + '%'
OR #HspOrganizationalName IS NULL
OR #HspOrganizationalName = '')
AND (LOWER(HspSiteNumber) LIKE LOWER(#HspSiteNumber)
OR #HspSiteNumber IS NULL OR #HspSiteNumber = '')
GROUP BY
CAST(StartedDateTime AS date)
ORDER BY
1
END
ELSE BEGIN
SELECT
CAST(DATEPART(WEEK, StartedDateTime) AS varchar(10)) Value,
COUNT(*) cnt
FROM
SubmittedSurveys
WHERE
(SurveyID = #SurveyID OR #SurveyID IS NULL)
AND (StartedDateTime >= #FromDate OR #FromDate IS NULL)
AND (StartedDateTime <= #ToDate OR #ToDate IS NULL)
AND (LOWER(ProvidedNameOfSubmitter) LIKE LOWER(#NameOfSubmitter) + '%'
OR #NameOfSubmitter IS NULL OR #NameOfSubmitter = '')
AND (LOWER(NameOfPrivacyContact) LIKE LOWER(#NameOfPrivacyContact) + '%'
OR #NameOfPrivacyContact IS NULL
OR #NameOfPrivacyContact = '')
AND (LOWER(HspOrganizationalName) LIKE LOWER(#HspOrganizationalName) + '%'
OR #HspOrganizationalName IS NULL
OR #HspOrganizationalName = '')
AND (LOWER(HspSiteNumber) LIKE LOWER(#HspSiteNumber)
OR #HspSiteNumber IS NULL OR #HspSiteNumber = '')
GROUP BY
CAST(DATEPART(WEEK, StartedDateTime) AS varchar(10))
ORDER BY
1
END
END
and here is the results
but in front end getting "Value" ="Date" instead of week value
Here is the code of front end
public static List<SubmittedSurveys> GetSurveyStatistic(int SubmittedSurveyId, DateTime
StartedDateTime, string NameOfSubmitter, string NameOfPrivacyContact, string
HspOrganizationalName, string HspSiteNumber,
DateTime CompletedDateTime,bool weekly)
{
try
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database _wohcDB = factory.Create("SurveyToolDBEntities");
// SqlDatabase _wohcDB = DatabaseFactory.CreateDatabase("SurveyToolDBEntities") as
SqlDatabase;
string sqlCommand = "[GetSurveyStatistic]";
DbCommand dbCommand = _wohcDB.GetStoredProcCommand(sqlCommand);
_wohcDB.AddInParameter(dbCommand, "#SurveyID", DbType.Int32, SubmittedSurveyId);
_wohcDB.AddInParameter(dbCommand, "#FromDate", DbType.DateTime, StartedDateTime);
_wohcDB.AddInParameter(dbCommand, "#ToDate", DbType.DateTime, CompletedDateTime);
_wohcDB.AddInParameter(dbCommand, "#NameOfSubmitter", DbType.String, NameOfSubmitter);
_wohcDB.AddInParameter(dbCommand, "#NameOfPrivacyContact", DbType.String, NameOfPrivacyContact);
_wohcDB.AddInParameter(dbCommand, "#HspOrganizationalName", DbType.String, HspOrganizationalName);
_wohcDB.AddInParameter(dbCommand, "#HspSiteNumber", DbType.String, HspSiteNumber);
_wohcDB.AddInParameter(dbCommand, "#weekly", DbType.String, weekly);
DataSet ds = _wohcDB.ExecuteDataSet(dbCommand);
_submittedSurvey = ReportsController.DbConverter.DataTable2List<SubmittedSurveys>(ds.Tables[0]);
//_submittedSurvey[0].SurveyReports = ReportsController.DbConverter.DataTable2List<Reports>(ds.Tables[1]);
}
catch (Exception ex)
{
string message = ex.Message.ToString();
}
return _submittedSurvey;
}
Here is the screenshot of front end where I am getting wrong value as a date instead of week
Can somebody help me to resolve this issue. This is so weird. i also tried to cast in int but getting error that date can not convert into int. I am not sure that why I am getting wrong data in front end and getting right data in backend?
Please help me.

Try to Change:
_wohcDB.AddInParameter(dbCommand, "#weekly", DbType.String, weekly);
To:
_wohcDB.AddInParameter(dbCommand, "#weekly", DbType.Boolean, weekly);

Just run the else part then it will work fine. with this query it will always go to if statement because of #Weekly =0.

Related

Date Format: No overload for method "ToString" takes 1 arguments

I stay with that error when I'm trying to format a date in my code:
Cmd.CommandText = #"
DECLARE #command varchar(5000);
DECLARE #RestoreList TABLE(DB_name VARCHAR(100), RS_name VARCHAR(100), RS_DateFinExercice DATE, RS_IsClosed VARCHAR(50));
SELECT #command = 'IF ''?'' IN (SELECT name FROM sys.databases WHERE HAS_DBACCESS(name) = 1 AND CASE WHEN state_desc = ''ONLINE'' THEN OBJECT_ID( QUOTENAME( name ) + ''.[dbo].[P_DOSSIER]'',''U'' ) END IS NOT NULL) BEGIN USE [?] SELECT DB_name = CAST(DB_NAME() AS VARCHAR(100)), RS_name = CAST(a.D_RaisonSoc AS VARCHAR(100)), RS_DateFinExercice = CAST((SELECT Max(v) FROM (VALUES (a.[D_FinExo01]), (a.[D_FinExo02]), (a.[D_FinExo03]),(a.[D_FinExo04]),(a.[D_FinExo05])) AS value(v)) AS DATE), RS_IsClosed = CAST((SELECT CASE WHEN (SUM (CASE WHEN JM_Cloture !=2 THEN 1 ELSE 0 END)>0) THEN '''' ELSE ''arc'' END FROM F_JMOUV) AS VARCHAR(50)) FROM [dbo].[P_DOSSIER] a INNER JOIN F_JMOUV b ON DB_name() = DB_NAME() GROUP BY D_RaisonSoc, D_FinExo01, D_FinExo02, D_FinExo03, D_FinExo04, D_FinExo05 HAVING COUNT(*) > 1 END'
INSERT INTO #RestoreList EXEC sp_MSforeachdb #command;
SELECT * FROM #RestoreList ORDER BY DB_name;";
SqlDataReader dr = Cmd.ExecuteReader();
List<DBtoRestore> dgUIDcollection = new List<DBtoRestore>();
if (dr.HasRows)
{
while (dr.Read())
{
DBtoRestore currentdgUID = new DBtoRestore
{
CUID_dbname = dr["DB_name"].ToString(),
CUID_RaisonSoc = dr["RS_name"].ToString(),
CUID_DateFinExercice = dr["RS_DateFinExercice"].ToString(),
CUID_IsClosed = dr["RS_IsClosed"].ToString()
};
dgUIDcollection.Add(currentdgUID);
}
}
dgDBtoRestore.ItemsSource = dgUIDcollection;
Cnx.Close();
The problem is on this line of code:
CUID_DateFinExercice = dr["RS_DateFinExercice"].ToString()
For now, my datagrid report date like 01/01/2020 00:00:00. In SQL, I have 01-01-2020 style.
I want to have the same style in my datagrid.
I have try something like ToString("dd-MM-yyyy") but it's in that context I've received the error.
Any idea to help me?
Convert to a DateTime and then call ToString on it:
Convert.ToDateTime(dr["RS_DateFinExercice"]).ToString("dd-MM-yyyy")
Solution :
CUID_DateFinExercice = ((DateTime)dr["RS_DateFinExercice"]).ToString("dd-MM-yyyy"),

Pass DECLARE parameters in SQL query

I have the following code:
SqlCommand command = new SqlCommand(
#"DECLARE #month int, #year int, #dateToCheck datetime;
SET #month = #month;
SET #year = #year;
SET #dateToCheck = dateadd(month, 1, datefromparts(#year, #month, 1))
SELECT p.name, dtc.cost_price, p.date_created
FROM [dbo].[Company_Local_Invoice_] claidig
JOIN Type_Company dtc on claidig.ID = dtc.id
WHERE p.date_created < #dateToCheck
AND (p.date_left is null or p.date_left >= #dateToCheck)", conn);
command.Parameters.Add("#month", SqlDbType.Int).Value = month;
command.Parameters.Add("#year", SqlDbType.Int).Value = year;
The problem is that I can't seem to pass my SET parameters using command.Parameter.Add() .
The error that I get is:
The variable name '#month' has already been declared. Variable names must be unique within a query batch or stored procedure.
Why is this and how can I work around this?
The point Gordon is making is that when you pass parameters to a sql string, it prepends the 'declare' statements from the parameter definitions. So, you don't need to do the declare for anything that's coming in as parameters. You still need to declare any variable that gets computed from the parameters though.
var commandText = #"
declare #dateToCheck datetime
set #dateToCheck = dateadd(month, 1, datefromparts(#year, #month, 1))
select
p.name, dtc.cost_price, p.date_created
from
dbo.[Company_Local_Invoice_] claidig
inner join
Type_Company dtc
on c
laidig.ID = dtc.id
where
p.date_created < #dateToCheck
and
(
p.date_left is null
or
p.date_left >= #dateToCheck
)";
var command = new SqlCommand(commandText, conn);
command.Parameters.Add("#month", SqlDbType.Int).Value = month;
command.Parameters.Add("#year", SqlDbType.Int).Value = year;
Just pass in the parameters and do the calculations in the query:
SELECT p.name, dtc.cost_price, p.date_created
FROM [dbo].[Company_Local_Invoice_] claidig
JOIN Type_Company dtc ON claidig.ID = dtc.id
CROSS APPLY (VALUES
(dateadd(month, 1, datefromparts(#year, #month, 1)))
) v(dateToCheck)
WHERE p.date_created < v.dateToCheck AND
(p.date_left is null or p.date_left >= v.dateToCheck);

Must declare the scalar variable "#ManagerID"

I have a Running Time Error:
Must declare the scalar variable \"#ManagerID
I'm Sure I Have Declare All Variables In My CLass And My Procudure
My Class Code:
public DataTable Select(int ID,string NameFa, string Address, int ManagerID, short TotalUnits, int ChargeMethodID)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("NameFa", typeof(string));
table.Columns.Add("Address", typeof(string));
table.Columns.Add("ManagerID", typeof(int));
table.Columns.Add("TotalUnits", typeof(short));
table.Columns.Add("ChargeMethodID", typeof(int));
try
{
con.Open();
SqlCommand command = new SqlCommand("dbo.SelectBuilding", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#ID", ID));
command.Parameters.Add(new SqlParameter("#NameFa", NameFa));
command.Parameters.Add(new SqlParameter("#Address", Address));
command.Parameters.Add(new SqlParameter("#ManagerID", ManagerID));
command.Parameters.Add(new SqlParameter("#TotalUnits", TotalUnits));
command.Parameters.Add(new SqlParameter("#ChargeMethodID", ChargeMethodID));
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
return table;
}
And My Procudure Code Is:
#ID int,
#NameFa nvarchar(150),
#Address nvarchar(MAX),
#ManagerID int,
#TotalUnits smallint,
#ChargeMethodID int
As
Begin
IF(#ID >0 )
Begin
Select ID,NameFa,Address,ManagerID,TotalUnits,ChargeMethodID From Buildings where ID = #ID
End
ELSE
Begin
Declare #sqlTxt nvarchar(MAX)
SET #sqlTxt = 'SELECT ID,NameFa,Address,ManagerID,TotalUnits,ChargeMethodID FROM Buildings where ID>0'
IF(#NameFa!= null)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND NameFa Like ''%#NameFa%'''
END
IF(#Address!= null)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND Address Like ''%#Address%'''
END
IF(#ManagerID > 0)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND ManagerID = #ManagerID'
END
IF(#TotalUnits > 0)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND TotalUnits = #TotalUnits'
END
IF(#ChargeMethodID > 0)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND ChargeMethodID = #ChargeMethodID'
END
EXEC (#sqlTxt);
End
END
And I want to use Select Function:
DataTable dt = new DataTable();
Buildings.Building bb = new Buildings.Building() {ID=0,NameFa="",Address="",ManagerID=OwnerID,TotalUnits=0,ChargeMethodID=0 };
dt = bu.Select(bb.ID,bb.NameFa,bb.Address,bb.ManagerID,bb.TotalUnits,bb.ChargeMethodID);
You are not passing the parameters to the exec statement. I would change it to sp_executesql which has an optional argument with parameters.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql
Edit: I strongly suggest getting rid of the exec and/or sp_executesql commands. Because depending on the input you could:
a) Get runtime errors due to user typing SQL string delimiters as a valid input. Example O'Hara as a surname.
b) A malicious user could mess badly with your database.
You could get similar result in a more simple way:
Select
ID,NameFa,Address,ManagerID,TotalUnits,ChargeMethodID
From
Buildings
where
(#Id = 0 or ID = #Id)
and (#NameFa = '' or NameFa = #NameFa)
and (#ManagerID = 0 or ManagerID = #ManagerID)
// repeat for the rest of the optional search conditions

Error converting data type nvarchar to bigint in C#

stored Procedure
ALTER PROCEDURE [dbo].[spInsertLoanMaster]
#TAc_no bigint
,#TAcc_no bigint
,#TAc_name nvarchar(50)
,#TV_no bigint
,#TJlg_no bigint
,#TPost_no bigint
,#TPhone_no1 bigint
,#TAct_no bigint
,#TLoan_amt bigint
,#TLoan_date date
,#TInt_rate bigint
,#TPay_mode nvarchar(max)
,#TPrin_inst nvarchar(max)
,#TGuar_name1 nvarchar(50)
,#TGuar_name2 nvarchar(50)
,#TChq_no bigint
,#TChq_date date
,#TGurAdd1 nvarchar(100)
,#TGurAdd2 nvarchar(100)
,#TGurPhone1 nvarchar(100)
,#TGurPhone2 nvarchar(100)
,#TPeriodInYear nvarchar(100)
,#TPeriod nvarchar(100)
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 Loan_Master (Ac_no,Acc_no , Ac_name,V_no,Jlg_no,Post_no,Act_no,phone_no1,Guar_name1,GurAdd1,GurPhone1,Guar_name2,GurAdd2,GurPhone2,Loan_amt,Loan_date ,Int_rate,PeriodInYear,Pay_mode,Prin_inst,Chq_date ,Chq_no,Period)values
(
#TAc_no
,#TAcc_no
,#TAc_name
,#TV_no
,#TJlg_no
,#TPost_no
,#TPhone_no1
,#TAct_no
,#TLoan_amt
,#TLoan_date
,#TInt_rate
,#TPay_mode
,#TPeriodInYear
,#TPrin_inst
,#TGuar_name1
,#TGuar_name2
,#TChq_no
,#TChq_date
,#TGurAdd1
,#TGurAdd2
,#TGurPhone1
,#TGurPhone2,
#TPeriod)
END
call this procedure
public void getInsert(Int64 Acno,Int64 Accno, string Acname, Int64 Vno, Int64 Jlgno, Int64 Postno, Int64 Actno, Int64 phoneno1, string Guarname1, string Guradd1, string GurPh1, string Guarname2, string Guradd2, string GurPh2,Int64 Loanamt, DateTime Loandate,Int64 Intrate, string PeriodYear, string Paymode, string Prininst, Int64 Chqno,DateTime Chqdate,string period1)
{
conobj.getconnection();
conobj.con.Open();
conobj.cmd = new SqlCommand("spInsertLoanMaster", conobj.con);
conobj.cmd.CommandType = CommandType.StoredProcedure;
conobj.cmd.Parameters.Add("#TAc_no", SqlDbType.BigInt).Value = Acno;
conobj.cmd.Parameters.Add("#TAcc_no", SqlDbType.BigInt).Value = Accno;
conobj.cmd.Parameters.Add("#TAc_name", SqlDbType.NVarChar).Value = Acname;
conobj.cmd.Parameters.Add("#TV_no", SqlDbType.BigInt).Value = Vno;
conobj.cmd.Parameters.Add("#TJlg_no", SqlDbType.BigInt).Value = Jlgno;
conobj.cmd.Parameters.Add("#TPost_no", SqlDbType.BigInt).Value = Postno;
conobj.cmd.Parameters.Add("#TAct_no", SqlDbType.BigInt).Value = Actno;
conobj.cmd.Parameters.Add("#TPhone_no1", SqlDbType.BigInt).Value = phoneno1;
conobj.cmd.Parameters.Add("#TGuar_name1", SqlDbType.NVarChar).Value = Guarname1;
conobj.cmd.Parameters.Add("#TGurAdd1", SqlDbType.NVarChar).Value = Guradd1;
conobj.cmd.Parameters.Add("#TGurPhone1", SqlDbType.NVarChar).Value = GurPh1;
conobj.cmd.Parameters.Add("#TGuar_name2", SqlDbType.NVarChar).Value = Guarname2;
conobj.cmd.Parameters.Add("#TGurAdd2", SqlDbType.NVarChar).Value = Guradd2;
conobj.cmd.Parameters.Add("#TGurPhone2", SqlDbType.NVarChar).Value = GurPh2;
conobj.cmd.Parameters.Add("#TLoan_date", SqlDbType.DateTime).Value = Loandate;
conobj.cmd.Parameters.Add("#TLoan_amt", SqlDbType.BigInt).Value = Loanamt;
conobj.cmd.Parameters.Add("#TInt_rate", SqlDbType.BigInt).Value = Intrate;
conobj.cmd.Parameters.Add("#TPeriodInYear", SqlDbType.NVarChar).Value = PeriodYear;
conobj.cmd.Parameters.Add("#TPay_mode", SqlDbType.NVarChar).Value = Paymode;
conobj.cmd.Parameters.Add("#TPrin_inst", SqlDbType.NVarChar ).Value = Prininst;
conobj.cmd.Parameters.Add("#TChq_no", SqlDbType.BigInt).Value = Chqno;
conobj.cmd.Parameters.Add("#TChq_date", SqlDbType.DateTime).Value = Chqdate;
conobj.cmd.Parameters.Add("#TPeriod", SqlDbType.NVarChar ).Value = period1;
conobj.cmd.ExecuteNonQuery();
conobj.con.Close();
}
form Coding
private void btnNewSave_Click(object sender, EventArgs e)
{
string s = "";
if (CMB_VillageNum.SelectedIndex >= 0)
{
s = CMB_VillageNum.Items[CMB_VillageNum.SelectedIndex].ToString ();
}
string s1 = "";
if (CMB_JLGNum.SelectedIndex >= 0)
{
s1 = CMB_JLGNum.Items[CMB_JLGNum.SelectedIndex].ToString();
}
string s2 = "";
if (CMB_ActiviNum.SelectedIndex >= 0)
{
s2 = CMB_ActiviNum.Items[CMB_ActiviNum.SelectedIndex].ToString();
}
string s3 = "";
if (CMB_PostNum.SelectedIndex >= 0)
{
s3 = CMB_PostNum.Items[CMB_PostNum.SelectedIndex].ToString();
}
string s4 = "";
if (CMB_Period.SelectedIndex >= 0)
{
s4 = CMB_Period.Items[CMB_Period.SelectedIndex].ToString();
}
//if (CMB_Period.SelectedIndex == 1)
//{
//string dateof = this.dateTimePicker1.Text;
//string dateto =this. dateTimePicker2.Text;
//objLoan.getInsert(Convert.ToInt64(txtAccNo.Text), txtName.Text, Convert.ToInt64(CMB_VillageNum.SelectedValue), Convert.ToInt64(CMB_JLGNum.SelectedValue), Convert.ToInt64(CMB_PostNum.SelectedValue)
// , Convert.ToInt64(CMB_ActiviNum.SelectedValue), Convert.ToInt64(txtPhone.Text), txtGurName1.Text, txtGurName2.Text, txtPhoneNum1.Text, txtPhoneNum2.Text, txtGur1Addresss.Text, txtGur2Addresss.Text, Convert.ToDateTime(dateTimePicker1.Text), Convert.ToInt64(txtLoanAmt.Text), Convert.ToInt64(txtRateOfInter.Text)
// , "0", txtPaymentMode.Text, txtPriInstall.Text, Convert.ToInt64(txtChequeNo.Text), Convert.ToDateTime(dateTimePicker2.Text), txtPeroid.Text);
//dateTimePicker1.Value.ToString("dd//MM//yyyy");
//dateTimePicker2.Value.ToString("dd//MM//yyyy");
objLoan.getInsert(Convert.ToInt64(txtAccNo.Text.Trim()), Convert.ToInt64(lblAccNum.Text.Trim()), txtName.Text, Convert.ToInt64(s.Trim()), Convert.ToInt64(s1.Trim()), Convert.ToInt64(s3.Trim())
, Convert.ToInt64(s2.Trim()), Convert.ToInt64(txtPhone.Text.Trim()), txtGurName1.Text, txtGur1Addresss.Text
, txtPhoneNum1.Text, txtGurName2.Text, txtGur2Addresss.Text, txtPhoneNum2.Text
, Convert.ToInt64(txtLoanAmt.Text.Trim()), Convert .ToDateTime (dateTimePicker1 .Text ),Convert.ToInt64(txtRateOfInter.Text.Trim()),(s4.Trim()), txtPaymentMode.Text,
txtPriInstall.Text, Convert.ToInt64(txtChequeNo.Text.Trim()), Convert .ToDateTime (dateTimePicker2 .Text ),txtPeroid.Text);
I'm trying to call this procedure with the usp_TimesheetsAuditsLoadAllbyId 42747, NULL command.
But I always get an error
Msg 8114, Level 16, State 5, Procedure
usp_TimesheetsAuditsLoadAllById, Line 9 Error converting data type
varchar to bigint.
The ID of TimesheetsAudits table is a bigint type. I tried several types of conversions and casts, but I'm really stuck right now.
Your parameters in the insert of your stored procedure do not match the variables passed.
The Insert Query and Value query having different order of Parameters and this caused issue the Insert statement. Try this for your Insert query,
ALTER PROCEDURE [dbo].[spInsertLoanMaster]
#TAc_no bigint
,#TAcc_no bigint
,#TAc_name nvarchar(50)
,#TV_no bigint
,#TJlg_no bigint
,#TPost_no bigint
,#TPhone_no1 bigint
,#TAct_no bigint
,#TLoan_amt bigint
,#TLoan_date date
,#TInt_rate bigint
,#TPay_mode nvarchar(max)
,#TPrin_inst nvarchar(max)
,#TGuar_name1 nvarchar(50)
,#TGuar_name2 nvarchar(50)
,#TChq_no bigint
,#TChq_date date
,#TGurAdd1 nvarchar(100)
,#TGurAdd2 nvarchar(100)
,#TGurPhone1 nvarchar(100)
,#TGurPhone2 nvarchar(100)
,#TPeriodInYear nvarchar(100)
,#TPeriod nvarchar(100)
AS
BEGIN --Act_no
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
insert Loan_Master
(
Ac_no, Acc_no , Ac_name, V_no, Jlg_no, Post_no, Act_no, phone_no1,
Guar_name1 ,GurAdd1, GurPhone1, Guar_name2,
GurAdd2, GurPhone2, Loan_amt, Loan_date, Int_rate,
PeriodInYear, Pay_mode, Prin_inst, Chq_date, Chq_no, Period
)
values
(
#TAc_no, #TAcc_no, #TAc_name, #TV_no, #TJlg_no, #TPost_no, #TAct_no, #TPhone_no1,
#TGuar_name1, #TGurAdd1, #TGurPhone1, #TGuar_name2,
#TGurAdd2, #TGurPhone2, #TLoan_amt, #TLoan_date, #TInt_rate,
#TPeriodInYear, #TPay_mode, #TPrin_inst, #TChq_date, #TChq_no, #TPeriod
)

Call SQL function with C#

I write this function in SQL:
ALTER FUNCTION Fn_CheckBill
(
#image AS image,
#number AS nvarchar(50),
#date AS nchar(10)
)
RETURNS bit
AS
BEGIN
DECLARE #flag bit;
IF EXISTS ( SELECT *
FROM tblBill
WHERE ((cast([Image] as varbinary(max)) = cast(#image as varbinary(max))) AND (Number = #number) AND ([Date] = #date)) )
BEGIN
SET #flag = 0
END
ELSE
BEGIN
SET #flag = 1
END
RETURN #flag
END
And write this code in my C# source code:
int flag;
try
{
objCommand = new SqlCommand("SELECT Fn_CheckBill(#image,#date,#number) AS int");
objCommand.CommandType = CommandType.Text;
objCommand.Parameters.AddWithValue("image", image);
objCommand.Parameters.AddWithValue("number", number);
objCommand.Parameters.AddWithValue("date", _Date);
using (objConnection = new SqlConnection(connenctString))
{
objConnection.Open();
objCommand.Connection = objConnection;
flag = int.Parse(objCommand.ExecuteScalar().ToString());
}
if (flag == 1)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
But It throw this exception when executed:
'Fn_CheckBill' is not a recognized function name.
Please help me to solve this problem :(
You need to supply the schema in any SQL function call
objCommand = new SqlCommand("SELECT dbo.Fn_CheckBill(#image,#date,#number) AS int");
I would consider rewriting this as an inline table valued function. Something like this:
create FUNCTION Fn_CheckBill
(
#image AS varbinary(max),
#number AS nvarchar(50),
#date AS nchar(10)
)
RETURNS table
AS
RETURN
SELECT CAST(count(*) as bit) as RowFound
FROM tblBill
WHERE [Image] = #image
AND Number = #number
AND [Date] = #date

Categories