Return string from SQL Procedure to C# - sql

I have a SQL create procedure query like this
USE KOST
GO
--Cabang means Branch in Bahasa.
CREATE PROCEDURE login_pro
--received parameter
#NoIDStaff VARCHAR(5),
#Password VARCHAR (50)
AS
--sent parameter
DECLARE #status INT
DECLARE #IDCabang VARCHAR(5)
--owner login
IF EXISTS(SELECT IDCabang, [Password]
FROM MsStaff
WHERE #NoIDStaff=NoIDStaff AND #Password=[Password]
AND NoIDStaff LIKE('B%'))
SET #status=1
--staff login
ELSE IF EXISTS(SELECT IDCabang, [Password]
FROM MsStaff
WHERE #NoIDStaff=NoIDStaff AND #Password=[Password]
AND NoIDStaff LIKE('A%'))
BEGIN
SELECT #IDCabang=IDCabang FROM MsStaff
SET #status=2
SET #IDCabang = (select IDCabang FROM Msstaff where #NoIDStaff=NoIDStaff AND #Password=[Password]
AND NoIDStaff LIKE('A%'))
END
--neither of them login
ELSE
set #status=0
select #status, #IDCabang
GO
The query returns value of the status but not the IDCabang.
What should I do so the value of the IDCabang will be returned?
this is my C# Code:
private void submit_Click(object sender, EventArgs e)
{
NoIDStaff = new SqlParameter();
Password = new SqlParameter();
SqlConnection con = new SqlConnection(strCon);
com = new SqlCommand();
com.Connection = con;
con.Open();
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "login_pro";
NoIDStaff.SqlDbType = SqlDbType.VarChar;
NoIDStaff.Size = 50;
NoIDStaff.ParameterName = "#NoIDStaff";
NoIDStaff.Value = username.Text.ToString();
NoIDStaff.Direction = ParameterDirection.Input;
Password.SqlDbType = SqlDbType.VarChar;
Password.Size = 50;
Password.ParameterName = "#Password";
Password.Value = password.Text.ToString();
Password.Direction = ParameterDirection.Input;
com.Parameters.Add(NoIDStaff);
com.Parameters.Add(Password);
int status;
string IDCabang;
status = Convert.ToInt16(com.ExecuteScalar());
IDCabang = Convert.ToString(com.ExecuteScalar());
//owner login
if (status == 1)
{
this.Hide();
frm = new Form2();
frm.Show();
}
//staff login
else if (status == 2)
{
this.Hide();
frm4 = new Form4(IDCabang);
frm4.Show();
}
else if (username.Text.Equals(""))
{
MessageBox.Show("Username Must be Filled!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (password.Text.Equals(""))
{
MessageBox.Show("Password Must be Filled!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Invalid Username or Password", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
}
I want to receive IDCabang as string, so I can send it to Form4. But it seems like, IDCabang doesn't return any value.

Try this
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
status = reader["Status"] == DBNull.Value ? 0 : (int)reader["Status"];
IDCabang = reader["IDCabang"] == DBNull.Value ? null : (string)reader["IDCabang"];
}

Did you try like this:
USE KOST
GO
--Cabang means Branch in Bahasa.
CREATE PROCEDURE login_pro(#IDCabang VARCHAR(5))
--received parameter
#NoIDStaff VARCHAR(5),
#Password VARCHAR (50)
AS
--sent parameter
DECLARE #status INT
--owner login
IF EXISTS(SELECT IDCabang, [Password]
FROM MsStaff
WHERE #NoIDStaff=NoIDStaff AND #Password=[Password]
AND NoIDStaff LIKE('B%'))
SET #status=1
--staff login
ELSE IF EXISTS(SELECT IDCabang, [Password]
FROM MsStaff
WHERE #NoIDStaff=NoIDStaff AND #Password=[Password]
AND NoIDStaff LIKE('A%'))
BEGIN
SELECT #IDCabang=IDCabang FROM MsStaff
SET #status=2
SET #IDCabang = (select IDCabang FROM Msstaff where #NoIDStaff=NoIDStaff AND #Password=[Password]
AND NoIDStaff LIKE('A%'))
END
--neither of them login
ELSE
set #status=0
select #status, #IDCabang
GO
Also SEE THIS

You're using ExecuteScalar, which is only ever going to look at the first row and first column of your return set: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
You really want to use ExecuteReader or something similar instead. In addition, I would alias your variables in your select so that you can reference them easier when you look for them (i.e., SELECT #status as Status, #IDCabang as IDCabang).
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
status = reader["Status"] == DBNull.Value ? 0 : (int)reader["Status"];
IDCabang = reader["IDCabang"] == DBNull.Value ? null : (string)reader["IDCabang"];
}
EDIT: In reference to Aaron Bertrand's comment, you could also set up an output parameter on your stored proc and read that. There's more detail on how to do that here: Get output parameter value in ADO.NET

Related

Get result from Stored Procedure then pass to WPF TextBox

I have this stored procedure that executes fine:
ALTER PROCEDURE [dbo].[SP_GENERATETICKET]
#RESULT AS VARCHAR(255) OUTPUT
AS
BEGIN
DECLARE #D AS DATETIME = GETDATE()
DECLARE #LASTTICKET AS VARCHAR(50) ;
DECLARE #NUM AS VARCHAR(50);
SET #LASTTICKET=(SELECT TOP 1 TICKETNO FROM tblTicket WHERE
MONTH(ENTRYVEHICLE ) = MONTH(#D ) ORDER BY TICKETNO DESC);
IF (CONVERT(VARCHAR(10),YEAR(#D),110) <> CONVERT(VARCHAR(10),YEAR(GETDATE()),110))--IF YEAR IS DIFFERENT, RESET SERIES
BEGIN
SET #NUM = '1'
END
ELSE
BEGIN
IF ISNULL(#LASTTICKET,'1') = '1'--IF MONTH IS DIFFERENT, RESET SERIES
BEGIN
SET #NUM ='1'
END
ELSE
BEGIN
SET #NUM = CAST(CAST (RIGHT(#LASTTICKET,5) AS INT) + 1 AS VARCHAR)
END
END
SET #RESULT = RIGHT(CONVERT(VARCHAR(10),#D,101),2) + '-' + LEFT(CONVERT(VARCHAR(10),#D,101),2) + '-' + RIGHT('0000'+CAST(#NUM AS VARCHAR),5)
SELECT #RESULT
END
I have this Code but it returns null
SqlConnection con = new SqlConnection(gsql.connectionString);
SqlCommand command = new SqlCommand("SP_GENERATETICKET", con);
try
{
con.Open();
command.CommandType = CommandType.StoredProcedure;
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar);
result.Direction = ParameterDirection.Output;
txtTicket.Text = (string)command.Parameters["#RESULT"].Value;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
What should I do?
there problem is there , you forgot to execute command
command.ExecuteNonQuery()
without executing command you want get result back.
also you forgot to add size for you varchar paramter , so add thing line
result.Size = 8000;
udpated in below code
you code will be , you need to use using to dispose things for you
using(SqlConnection con = new SqlConnection(gsql.connectionString))
{
using(SqlCommand command = new SqlCommand("SP_GENERATETICKET", con))
{
try
{
con.Open();
command.CommandType = CommandType.StoredProcedure;
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar);
result.Size = 8000;//add parameter size
result.Direction = ParameterDirection.Output;
command.ExecuteNonQuery();//this line need to be added
txtTicket.Text = (string)command.Parameters["#RESULT"].Value;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Parameters are a good practice but for output you cannot have SQL injection (that I know of).
con.Open();
command.CommandType = CommandType.StoredProcedure;
txtTicket.Text = (string)command.ExecuteScalar();
For size you can use this syntax:
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar, 800);

I've tried different ways but still it's throwing an error that cannot convert varchar to int

private void button_submit_Click(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=SQLNCLI11;Data Source=.;Integrated Security=SSPI;Initial Catalog=AdventureWorks2012");
cmd = new OleDbCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_empinfo";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#bid",textBox_BID.Text);
cmd.Parameters.AddWithValue("#job",SqlDbType.VarChar).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#gender",SqlDbType.VarChar).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#maritalstatus",SqlDbType.VarChar).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
label_Job.Text =label_Job.Text + "" + cmd.Parameters["#job"].Value.ToString();
label_gender.Text=label_gender.Text + "" + cmd.Parameters["#gender"].Value.ToString();
label_MStatus.Text=label_MStatus.Text + "" + cmd.Parameters["#maritalstatus"].Value.ToString();
}
My stored procedure with input and output parameters:
alter PROC USP_EMPINFO
#bid AS varchar(20),
#job as varchar(20) output,
#gender as varchar(20) output,
#maritalstatus as varchar(20) output
as
begin
select #Job=JobTitle,#Gender=Gender,#maritalstatus=MaritalStatus from humanresources.employee
where BusinessEntityID = #bid
end
I can only assume that BusinessEntityID is an int (maybe even an identifier). In that case, I would define the sproc parameter #bid as that same field type (int, if that's what it is). The sproc definition, then, wouldn't allow a non-int value to be passed in.
Then, change the c# code to
cmd.Parameters.Add("#bid",SqlDbType.Int).Value=int.Parse(textBox_BID.Text.Trim()); //trim because you're passing in a string that might be padded
If it blows up at that line, you'll know that even c# can't convert the value to an int, so you'll need to do extra field validation work.

How to update Columns if value is not NULL

I want to update any columns of table TBL_Log if value entered from C# is not NULL. Here is my stored procedure:
Alter PROCEDURE [dbo].[SP_Update_User]
(#User_id as int,#User_Names as nvarchar(max),#End as char(8),#Start as nvarchar(max) ,#Count as int)
AS
BEGIN
UPDATE [dbo].[TBL_Log]
SET User_Names = #User_Names
,[Start] = #start
,[End] = #End
,[Count] = #Count
where User_id = #User_id
END
I have tried to make this work but have not been successful.
code in class D1:
public static DataSet Update_User(int #User_id, string #User_Names, string #End, string #Start, int #Count)
{
SqlConnection myConnection = new SqlConnection(strConecctionString);
SqlDataAdapter sqlcmd = new SqlDataAdapter("SP_Update_UserData_Bot", myConnection);
sqlcmd.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parameterID_category_ID = new SqlParameter("#User_id", SqlDbType.Int);
parameterID_category_ID.Value = User_id;
sqlcmd.SelectCommand.Parameters.Add(parameterID_category_ID);
SqlParameter parameterID_Part_ID = new SqlParameter("#User_Names", SqlDbType.Int);
parameterID_Part_ID.Value = User_Names;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Part_ID);
SqlParameter parameterID_Series_ID = new SqlParameter("#End", SqlDbType.Char);
parameterID_Series_ID.Value = End;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Series_ID);
SqlParameter parameterID_Model_ID = new SqlParameter("#start", SqlDbType.NVarChar);
parameterID_Model_ID.Value = start;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Model_ID);
SqlParameter parameterID_Count = new SqlParameter("#Count", SqlDbType.Int);
parameterID_Count.Value = Count;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Count);
sqlcmd.SelectCommand.CommandTimeout = int.MaxValue;
DataSet DS = new DataSet();
sqlcmd.Fill(DS);
return DS;
}
This will update only the values that are not null. If the value is null, the column is updated back to its own value.
UPDATE [dbo].[TBL_Log]
SET User_Names = isnull(#User_Names, User_Names)
, [Start] = isnull(#start, [Start])
, [End] = isnull(#End, [End])
, [Count] = isnull(#Count, [Count])
where User_id = #User_id
You should show your .Net code. Probably the best place to add the check is in .NET and don't call the stored procedure if the value you are worried about is NULL.
Also you must specify which value shouldn't be null, but assuming you meant any of them you can do:
IF (#User_Names IS NULL OR #start IS NULL OR #End IS NULL OR #Count IS NULL OR #User_Id IS NULL)
BEGIN
RETURN
END
That will exit of the stored procedure if any of the parameters is null without updating the table
Given you c# code you can either don't call the stored procedure when a value is null or throw an exception. Also you should consider using DateTime instead of string for date values.
You can do the following in your c# code:
if (#User_Names == null || #End == null || #Start == null)
return;
Or preferably
if (#User_Names == null || #End == null || #Start == null)
throw new ArgumentNullException();
You can even check each parameter individually and pass its name as parameter to the Exception to give a meaningful error message.
Your commented out logic is fine:
UPDATE [dbo].[TBL_Log]
SET User_Names = #User_Names,
[Start] = #start,
[End] = #End,
[Count] = #Count
where User_id = #User_id and
(#User_Names is not null and
#AkharinBazdid is not null and
#Pid_Bazdid IS NOT NULL and
#C_Bazdid IS NOT NULL
);
You can also use IF if you prefer.
Notes:
Don't use SQL keywords and reserved words as column names. The escape characters just get in the way.
If start and end are date/times, then use the appropriate types. Don't use strings.

sql server procedure is not returning data

My Sql Procedure is Working perfectly. But when I call it from Class it does not returns data. And I get this Error. Column 'Territory_Name' does not belong to table . I debugged the code and found that All parameters are getting passed correctly, but the procedure is not returning any data. If anyone have idea then please help me.
My Stored Procedure is:
ALTER PROCEDURE dbo.SPFilterCRMRequests
(
/* for Time Span */
#WeekList varchar(50) = null,
#MonthList varchar(50) = null,
#YearList varchar(50) = null,
#QuaterList varchar(50) = null,
/* for other specific criteria */
#PriorityList varchar(50) = null,
#Division_IdList varchar(50) = null,
#CRM_Service_Type_IdList varchar(50) = null,
#CRM_Notation_IdList varchar(50) = null,
#CRM_State_IdList varchar(50) = null,
#Service_State_IdList varchar(50) = null,
#Estimated_Amount float
/* for Designation
#Requester varchar(20),
#Suggester varchar(20) */
)
AS
SET NOCOUNT ON
/*Declare #date3 DateTime = CONVERT(date,'2/8/2013 5:17:00 PM')*/
DECLARE #sql nvarchar(4000)
SELECT #sql='SELECT
CRMDR.Id as Id,
LEFT(GEOTREE.GEONAME,15) as Territory_Name,
CRMDR.Request_For_Id as Request_For_Id,
DRMST.DRNAME as Request_For_Name,
USERSTBM.USERNAME as Requester_Name,
Division.Div_Name as Division_Name,
USERSABM.USERNAME as Suggester_Name,
CRMDR.Estimated_Amount as Estimated_Amount,
CRMDR.Actual_Amount as Actual_Amount,
CRMDR.Compute_Priority as Compute_Priority,
CRMNotation.Notation_Name as CRM_Notation_Name,
CRMServiceType.ServiceName as CRM_Service_Type_Name,
CRMDR.Deadline as Deadline,
CRMDR.Executed_Date as Executed_Date,
CRMDR.Date_Created as Date_Created,
CRMDR.Compute_CRM_State as Compute_CRM_State,
CRMDR.Compute_Service_State as Compute_Service_State
From [CRM].[dbo].[CRM_Doctor_Request] AS CRMDR
JOIN [ASES].[dbo].[USERS] AS USERSTBM
ON CRMDR.Requester COLLATE SQL_Latin1_General_CP1_CI_AS = USERSTBM.RID COLLATE SQL_Latin1_General_CP1_CI_AS
JOIN [ASES].[dbo].[USERS] AS USERSABM
ON CRMDR.Suggester COLLATE SQL_Latin1_General_CP1_CI_AS = USERSABM.RID COLLATE SQL_Latin1_General_CP1_CI_AS
JOIN [ASES].[dbo].[GEOTREE] AS GEOTREE
ON CRMDR.Territory COLLATE SQL_Latin1_General_CP1_CI_AS = GEOTREE.RID COLLATE SQL_Latin1_General_CP1_CI_AS
JOIN [ASES].[dbo].[DRMST] AS DRMST
ON CRMDR.Request_For_Id COLLATE SQL_Latin1_General_CP1_CI_AS = DRMST.MDLNO COLLATE SQL_Latin1_General_CP1_CI_AS
JOIN [CRM].[dbo].[CRM_Request_For_Type] AS CRMReqForType
ON CRMDR.CRM_Request_For_Type_Id = CRMReqForType.Id
JOIN [CRM].[dbo].[CRM_Notation] AS CRMNotation
ON CRMDR.CRM_Notation_Id = CRMNotation.Id
JOIN [CRM].[dbo].[CRM_Service_Type] AS CRMServiceType
ON CRMDR.CRM_Service_Type_Id = CRMServiceType.Id
JOIN [CRM].[dbo].[Division] AS Division
ON CRMDR.Division_Id = Division.Id
WHERE CRMDR.Is_Deleted=0 '
If (#MonthList) IS NOT NULL
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (' + #MonthList + ') '
If (#YearList) IS NOT NULL
SELECT #sql=#sql + ' AND (CRMDR.Date_Created) in (' + #YearList + ') '
If (#WeekList) IS NOT NULL
BEGIN
DECLARE #DateCondition varchar(1000)
DECLARE #ColumnName varchar(50) = 'CRMDR.Date_Created'
-- pass the columnname on which condition needs to be aaplied
EXEC dbo.SPWhereconditionForMultipleWeeks #WeekList, #ColumnName, #DateCondition OUTPUT
SELECT #DateCondition
-- if (LEN(#DateCondition) > 0 )
SELECT #sql=#sql + ' AND '+ SUBSTRING(#DateCondition, 1, LEN(#DateCondition)-3)
END
If (#QuaterList) IS NOT NULL
BEGIN
DECLARE #MonthsList varchar(1000)
EXEC dbo.SPGetMonthsListforMultipleQuaters #QuaterList, #MonthsList OUTPUT
SELECT #MonthsList
-- print #MonthsList
-- if (LEN(#MonthsList) > 0 )
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in ('
+ SUBSTRING(#MonthsList, 1, LEN(#MonthsList)-1) +')'
END
If (#PriorityList) IS NOT NULL
SELECT #sql=#sql + ' AND Priority in (' + #PriorityList + ') '
If (#Division_IdList) IS NOT NULL
SELECT #sql=#sql + ' AND Division_Id in (' + #Division_IdList + ') '
If (#CRM_Service_Type_IdList) IS NOT NULL
SELECT #sql=#sql + ' AND CRM_Service_Type_Id in (' + #CRM_Service_Type_IdList + ') '
If (#CRM_Notation_IdList) IS NOT NULL
SELECT #sql=#sql + ' AND CRM_Notation_Id in (' + #CRM_Notation_IdList + ') '
If (#Estimated_Amount) IS NOT NULL
SELECT #sql=#sql + ' AND Estimated_Amount > (#Estimated_Amount) '
If (#CRM_State_IdList) IS NOT NULL
SELECT #sql=#sql + ' AND CRM_State_Id in (' + #CRM_State_IdList + ') '
If (#Service_State_IdList) IS NOT NULL
SELECT #sql=#sql + ' AND Service_State_Id in (' + #Service_State_IdList + ') '
SELECT #sql=#sql + ' ORDER BY CRMDR.Id DESC '
--print #sql
EXEC sp_executesql #sql, N' #MonthList varchar(50),
#YearList varchar(50),
#QuaterList varchar(50),
#PriorityList varchar(50),
#Division_IdList varchar(50),
#CRM_Service_Type_IdList varchar(50),
#CRM_Notation_IdList varchar(50),
#Estimated_Amount float,
#CRM_State_IdList varchar(50),
#Service_State_IdList varchar(50) ',
#MonthList,
#YearList,
#QuaterList,
#PriorityList,
#Division_IdList,
#CRM_Service_Type_IdList,
#CRM_Notation_IdList,
#Estimated_Amount,
#CRM_State_IdList,
#Service_State_IdList
RETURN
My Class Calling the Procedure :
public static List<CRM_Doctor_Request> FilterCRM_Doctor_Request_Details(string WeekList, string MonthList, string YearList, string QuaterList, string PriorityList, string Division_IdList, string CRM_Service_Type_IdList, string CRM_Notation_IdList, string CRM_State_IdList, string Service_State_IdList, float Estimated_Amount)
{
string proc = "SPFilterCRMRequests";
List<SqlParameter> arrParam = new List<SqlParameter>();
SqlParameter pWeekList = new SqlParameter("#WeekList", SqlDbType.VarChar);
SqlParameter pMonthList = new SqlParameter("#MonthList", SqlDbType.VarChar);
SqlParameter pYearList = new SqlParameter("#YearList", SqlDbType.VarChar);
SqlParameter pQuaterList = new SqlParameter("#QuaterList", SqlDbType.VarChar);
SqlParameter pPriorityList = new SqlParameter("#PriorityList", SqlDbType.VarChar);
SqlParameter pDivision_IdList = new SqlParameter("#Division_IdList", SqlDbType.VarChar);
SqlParameter pCRM_Service_Type_IdList = new SqlParameter("#CRM_Service_Type_IdList", SqlDbType.VarChar);
SqlParameter pCRM_Notation_IdList = new SqlParameter("#CRM_Notation_IdList", SqlDbType.VarChar);
SqlParameter pCRM_State_IdList = new SqlParameter("#CRM_State_IdList", SqlDbType.VarChar);
SqlParameter pService_State_IdList = new SqlParameter("#Service_State_IdList", SqlDbType.VarChar);
SqlParameter pEstimated_Amount = new SqlParameter("#Estimated_Amount", SqlDbType.Float);
pWeekList.Value = WeekList;
pMonthList.Value = MonthList;
pYearList.Value = YearList;
pQuaterList.Value = QuaterList;
pPriorityList.Value = PriorityList;
pDivision_IdList.Value = Division_IdList;
pCRM_Service_Type_IdList.Value = CRM_Service_Type_IdList;
pCRM_Notation_IdList.Value = CRM_Notation_IdList;
pCRM_State_IdList.Value = CRM_State_IdList;
pService_State_IdList.Value = Service_State_IdList;
pEstimated_Amount.Value = Estimated_Amount;
arrParam.Add(pWeekList);
arrParam.Add(pMonthList);
arrParam.Add(pYearList);
arrParam.Add(pQuaterList);
arrParam.Add(pPriorityList);
arrParam.Add(pDivision_IdList);
arrParam.Add(pCRM_Service_Type_IdList);
arrParam.Add(pCRM_Notation_IdList);
arrParam.Add(pCRM_State_IdList);
arrParam.Add(pService_State_IdList);
arrParam.Add(pEstimated_Amount);
DataTable table = DataProvider.SelectStoreProcedure(proc, arrParam);
List<CRM_Doctor_Request> ListCRM_Doctor_Request = new List<CRM_Doctor_Request>();
foreach (DataRow row in table.Rows)
{
CRM_Doctor_Request CRM_Doctor_RequestObj = new CRM_Doctor_Request();
CRM_Doctor_RequestObj.Territory_Name = Convert.ToString(row["Territory_Name"]);
CRM_Doctor_RequestObj.Request_For_Id = Convert.ToString(row["Request_For_Id"]);
CRM_Doctor_RequestObj.Request_For_Name = Convert.ToString(row["Request_For_Name"]);
CRM_Doctor_RequestObj.Requester_Name = Convert.ToString(row["Requester_Name"]);
CRM_Doctor_RequestObj.Division_Name = Convert.ToString(row["Division_Name"]);
CRM_Doctor_RequestObj.Suggester_Name = Convert.ToString(row["Suggester_Name"]);
CRM_Doctor_RequestObj.Id = Convert.ToInt32(row["Id"]);
CRM_Doctor_RequestObj.Compute_Priority = Convert.ToString(row["Compute_Priority"]);
CRM_Doctor_RequestObj.CRM_Notation_Name = Convert.ToString(row["CRM_Notation_Name"]);
CRM_Doctor_RequestObj.CRM_Service_Type_Name = Convert.ToString(row["CRM_Service_Type_Name"]);
CRM_Doctor_RequestObj.Compute_CRM_State = Convert.ToString(row["Compute_CRM_State"]);
CRM_Doctor_RequestObj.Compute_Service_State = Convert.ToString(row["Compute_Service_State"]);
ListCRM_Doctor_Request.Add(CRM_Doctor_RequestObj);
}
return ListCRM_Doctor_Request;
}
code of DataProvider.SelectStoreProcedure:
class DataProvider
{
public static string connectionString = ConfigurationManager.ConnectionStrings["connect_str"].ConnectionString;
public static DataTable SelectStoreProcedure(string ProcName, List<SqlParameter> ParaArr)
{
DataTable data = new DataTable();
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand(ProcName, cn);
foreach (SqlParameter para in ParaArr)
{
cmd.Parameters.Add(para);
}
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(data);
cn.Close();
return data;
}
}
This looks so messy; Since you are executing more than one query, I think you need to fill data into a DataSet and take the 0th Table or fill Datatable with results from the correct query.
Also you can reduce your code by half with Parameters.AddWithValue() and use using with the connection object.
//Your method
DataSet data = new DataSet(); //Note Dataset here ****
string connectionString = ConfigurationManager.ConnectionStrings["connect_str"].ConnectionString;
using(SqlConnection cn = new SqlConnection(connectionString))
{
string proc = "SPFilterCRMRequests";
SqlCommand cmd = new SqlCommand(proc, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#WeekList", WeekList);
cmd.Parameters.AddWithValue("#MonthList", pMonthList);
cmd.Parameters.AddWithValue("#YearList", pYearList);
cmd.Parameters.AddWithValue("#QuaterList", pQuaterList);
cmd.Parameters.AddWithValue("#PriorityList", pPriorityList);
cmd.Parameters.AddWithValue("#Division_IdList", pDivision_IdList);
cmd.Parameters.AddWithValue("#CRM_Service_Type_IdList", pCRM_Service_Type_IdList);
cmd.Parameters.AddWithValue("#CRM_Notation_IdList", pCRM_Notation_IdList);
cmd.Parameters.AddWithValue("#CRM_State_IdList", pCRM_State_IdList);
cmd.Parameters.AddWithValue("#Service_State_IdList", pService_State_IdList);
cmd.Parameters.AddWithValue("#Estimated_Amount", pEstimated_Amount);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cn.Open();
da.Fill(data);
}
List<CRM_Doctor_Request> ListCRM_Doctor_Request =
new List<CRM_Doctor_Request>();
foreach (DataRow row in data.Tables[0].Rows) //**** Note 0th table here ******
{
//rest of the code
}
//...
Your problem is that you are trying to fill a table (with no schema defined)
change DataTable data = new DataTable(); to DataSet data = new DataSet();
and DataTable table = data to DataTable table = data.Tables[0];
and your schema will be automatically generated and everything should work.
**EDIT**
Try building your query up from this setup...
Define this Stored Procedure
CREATE PROCEDURE [dbo].[TestProc1]
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX) = 'SELECT 1 x UNION ALL SELECT 2'
EXEC sp_executesql #sql
END
Create a test app containing just this code
class Program
{
public const string ConnectionString = #"???";
static void Main(string[] args)
{
var t = Execute("TestProc1");
Trace.Assert(t.Rows.Count == 2);
}
private static DataTable Execute(string sql)
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var command = new SqlCommand(sql, connection))
{
command.CommandType = CommandType.StoredProcedure;
var da = new SqlDataAdapter(command);
var ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
}
}
}
Where the connection string is your connection string.
That will work and it is functionally equivalent to what you are doing. Once you have that working try building it up to match your specific situation

execute a stored procedure that returns a " completed succesfully " clue

i have a stored procedure
UPDATE tblTime
SET TimeOut = DATEADD(HOUR,8,TimeIn)
WHERE tId =
(
SELECT MAX(tId)
FROM tblTime
WHERE UserId = 3571
)
although there's no question really, in that case if it did succeed in this query
cause even if the field is empty or if it has value,
it will in this case succeed
but i do need it for future other queries... and also ,
in this case i want the C# code to report
not only that it was requesting query to be execute - meaning it did happen,
but to get an actual answer from sql server
as a return value that c# could use or turn into Boolean
i have managed to do somthing about this so i can specify a condition inside sql server stored proc
declare an OUTPUT variable(PARAMETER) then
set its value to say 1 if condition is met and -1 if not
then
in c# set a function as follows
in this example outpout parameter is named ERROR
public static int UpdateTblViaStoredPRoc(string SPname, int UserID)
{
int message = 0;
using (SqlConnection con = new SqlConnection("server=(local);Initial Catalog=****DBNAME HERE***;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand(SPname, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Uid", UserID);
cmd.Parameters.Add("#ERROR", SqlDbType.Int);
cmd.Parameters["#ERROR"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
message =(int) cmd.Parameters["#ERROR"].Value;
con.Close();
}
return message;
}
stored proc is then allways following the same pattern
declare ERROR parameter, set a condition to output the ERROR accordingly :
ALTER PROCEDURE [dbo].[nameofProc]
#UId Int, #ERROR int OUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TimeOtVal varchar(50)
set #TimeOtVal = (SELECT CASE WHEN [TimeOut] IS NULL THEN '' ELSE CONVERT(NVARCHAR,[TimeOut]) END FROM tblTime WHERE tId = ( SELECT MAX(tId) FROM tblTime WHERE UserId = #UId))
IF (#TimeOtVal = '') -- condition for the update
BEGIN -- now action is taken if condition is met
SET NOCOUNT ON;
UPDATE tblTime SET TimeOut = DATEADD(HOUR,8,TimeIn) WHERE tId = ( SELECT MAX(tId) FROM tblTime WHERE UserId = #UId)
SET #ERROR = 1
END
else
BEGIN -- Other wise , if condition isnot met
SET #ERROR = -1
END
END
so it does what you want only if you allowed it by the condition
then reports the action so you can handle it in program code behind .