Get result from Stored Procedure then pass to WPF TextBox - sql

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);

Related

How can I sent variables to a stored procedure using GridControl

I'm using DevExpress's GridControl on Windows Forms, GridControl Give me the option to call a stored procedure but with default values, I need that the user input values so it can search using the stored procedure.
This is my main form:
In the left you can see that the user can insert the values that needs the stored procedure to be used.
This is my stored procedure
ALTER PROCEDURE [dbo].[SPS_PronosticoStock]
#IdProducto INT,
#IdBodega INT,
#FechaInicio DATE,
#FechaFin DATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Contador INT, -- Variable que aumenta hasta llegar a #Rango para el ciclo While
#Rango INT, -- Diferencia de dìas entre #FechaInicio y #FechaFin
#FechaDisplayed DATE, -- Variable que aumentara desde #FechaInicio hasta #FechaFin
#Stock INT
SET #Rango = DATEDIFF(DAY,#FechaInicio , #FechaFin)
SET #Contador = 0
SET #FechaDisplayed = #FechaInicio
SET #Stock = (SELECT Stock FROM Tbl_ProductoBodega WHERE IdProducto = #IdProducto AND IdBodega = #IdBodega)
--Inicia Ciclo WHILE
WHILE #Contador <= #Rango
BEGIN
SELECT
#FechaDisplayed, Tbl_ProductoBodega.Referencia, (#Stock), Tbl_ProductoBodega.ADU,
[Vs_InventarioEnTransitoAcumulado_BETA].CantTotalInsumo, Tbl_ProductoBodega.IdProducto,
Tbl_ProductoBodega.IdBodega
FROM
Tbl_ProductoBodega
INNER JOIN
[Vs_InventarioEnTransitoAcumulado_BETA] ON Tbl_ProductoBodega.IdProducto = [Vs_InventarioEnTransitoAcumulado_BETA].IdProducto
WHERE
Tbl_ProductoBodega.IdProducto = #IdProducto
AND Tbl_ProductoBodega.IdBodega = #IdBodega
--Actualiza las variables locales
SET #FechaDisplayed = DATEADD(DAY, 1, #FechaDisplayed)
SET #Contador = #Contador + 1
SET #Stock= (#Stock) - (SELECT ADU FROM Tbl_ProductoBodega
WHERE IdProducto = #IdProducto AND IdBodega = #IdBodega) +
(SELECT CantTotalInsumo FROM [Vs_InventarioEnTransitoAcumulado_BETA]
WHERE IdProducto = #IdProducto AND IdBodega = #IdBodega)
END
--Finaliza ciclo While
END
The values that have an # are the values that the user needs to input to the software
This is the code I've been working on:
DataTable dt = new DataTable();
String conStr = "Data Source=MSSQLSERVERWA;Initial Catalog=WA_PRUEBAS";
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("SPS_PronosticoStock", con);
com.Parameters.AddWithValue(" #IdProducto", Convert.ToInt32(textBox3.Text));
com.Parameters.AddWithValue("#IdBodega", Convert.ToInt32(textBox4.Text));
com.Parameters.AddWithValue("#FechaInicio", Convert.ToInt32(textBox1.Text));
com.Parameters.AddWithValue("#FechaFin", Convert.ToInt32(textBox2.Text));
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
try
{
con.Open();
da.Fill(dt);
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
da.Fill(dt);
gridControl1.DataSource = dt;

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 use the return value of stored procedure in asp.net?

I use this stored procedure for get the number of records
ALTER PROCEDURE [dbo].[Asbabbazi_A]
#count int output
AS
BEGIN
if(#count=0)
set #count =( select count(*) from dbo.Table_asbabbazi where (active= 0))
end
now I want use the #count in my project.I wrote this codes for use the #count in method.
SqlConnection con = new SqlConnection(constr);
cmd.Connection = con;
con.Open();
DataAdapter.SelectCommand = cmd;
DataSet ds = new DataSet("haftehbazardb");
SqlCommandBuilder bldr = new SqlCommandBuilder(DataAdapter);
SqlParameter returnParameter = cmd.Parameters.Add("count", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
DataAdapter.Fill(ds, Table_asbabbazi);
countrecords = (int)returnParameter.Value;
this codes have no error but when i use the (countrecords ) in my project the value of (countrecords ) is zero that is not right .
Please help
If you want to get the value as the output of the stored procedure, you will need to return it.
ALTER PROCEDURE [dbo].[Asbabbazi_A]
#count int output
AS
BEGIN
if(#count=0)
set #count =( select count(*) from dbo.Table_asbabbazi where (active= 0))
return #count
end
You are confusing output parameters with a return value.
Return value is generally used to indicate the status of your procedure, it will be 0 if not specified, e.g.
CREATE PROCEDURE dbo.TestProc #Out INT OUTPUT
AS
BEGIN
BEGIN TRY
SET #Out = 1 / 0;
RETURN 0;
END TRY
BEGIN CATCH
SET #Out = 0;
RETURN 1;
END CATCH
END
Then calling this with T-SQL;
DECLARE #out INT, #return INT;
EXECUTE #Return = dbo.TestProc #out OUT;
SELECT [Return] = #return, [out] = #out;
Will give:
Return | out
-------+-----
1 | 0
Since 0 is the default return value, this is why you are getting 0 out from returnParameter, you need to use ParameterDirection.Output:
SqlParameter returnParameter = cmd.Parameters.Add("count", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.Output;

Return string from SQL Procedure to C#

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

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