Count Data from Database using stored Procedure w/ inner join [closed] - c#

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm having a problem counting data w/ inner join.
I want to count how many cottages are available, here are my tables:
here's my code in class getting the cottage number.
public void CheckCottages()
{
con.Close();
SqlCommand comUmbrella = new SqlCommand("CountCottages", con);
comUmbrella.CommandType = CommandType.StoredProcedure;
comUmbrella.Parameters.Add("#CottageType", SqlDbType.NVarChar).Value = "Umbrella";
comUmbrella.Parameters.Add("#ReservedDate", SqlDbType.DateTime).Value = this.ARRIVAL;
con.Open();
comUmbrella.ExecuteNonQuery();
drUmbrella = comUmbrella.ExecuteReader();
if (drUmbrella.Read())
{
this.UMBRELLA = drUmbrella.GetInt32(drUmbrella.GetOrdinal("Rows"));
}
con.Close();
SqlCommand comNativeKubo = new SqlCommand("CountCottages", con);
comNativeKubo.CommandType = CommandType.StoredProcedure;
comNativeKubo.Parameters.Add("#CottageType", SqlDbType.NVarChar).Value = "Native Kubo";
comNativeKubo.Parameters.Add("#ReservedDate", SqlDbType.DateTime).Value = this.ARRIVAL;
con.Open();
comNativeKubo.ExecuteNonQuery();
drKubo = comNativeKubo.ExecuteReader();
if (drKubo.Read())
{
this.NATIVEKUBO = drKubo.GetInt32(drKubo.GetOrdinal("Rows"));
}
con.Close();
SqlCommand comTreeHouse = new SqlCommand("CountCottages", con);
comTreeHouse.CommandType = CommandType.StoredProcedure;
comTreeHouse.Parameters.Add("#CottageType", SqlDbType.NVarChar).Value = "Tree house";
comTreeHouse.Parameters.Add("#ReservedDate", SqlDbType.DateTime).Value = this.ARRIVAL;
con.Open();
comTreeHouse.ExecuteNonQuery();
drTree = comTreeHouse.ExecuteReader();
if (drTree.Read())
{
this.TREEHOUSE = drTree.GetInt32(drTree.GetOrdinal("Rows"));
}
con.Close();
SqlCommand comPavillion = new SqlCommand("CountCottages", con);
comPavillion.CommandType = CommandType.StoredProcedure;
comPavillion.Parameters.Add("#CottageType", SqlDbType.NVarChar).Value = "Pavillion";
comPavillion.Parameters.Add("#ReservedDate", SqlDbType.DateTime).Value = this.ARRIVAL;
con.Open();
comPavillion.ExecuteNonQuery();
drPavillion = comPavillion.ExecuteReader();
if (drPavillion.Read())
{
this.PAVILLION = drPavillion.GetInt32(drPavillion.GetOrdinal("Rows"));
}
}
Here's my stored Procedure:
ALTER PROCEDURE dbo.CountCottages
(
#CottageType nvarchar(50),
#ReservedDate datetime
)
AS
SELECT count(dbo.Cottages.CottageName)
FROM dbo.Cottages INNER JOIN
dbo.ResortTransactions ON dbo.Cottages.CottageID = dbo.ResortTransactions.CottageID
where dbo.Cottages.CottageType=#CottageType and dbo.ResortTransactions.Status != 'Cancelled' and dbo.ResortTransactions.ReservedDate != #ReservedDate
RETURN
What's wrong to my code? I hope someone can help me :)
Thanks in advance!

Since there's not much information about how your data is used, here's a guess. I'm assuming you want a count of cottages where there is a transaction where 1) the status is not cancelled and 2) the date is equal to the reservation date. If so here's the query:
SELECT count(dbo.Cottages.CottageName)
FROM dbo.Cottages
WERE CottageType=#CottageType
AND CottageID NOT IN
(SELECT CottageID FROM dbo.ResortTransactions
WHERE Status != 'Cancelled'
AND ReservedDate = #ReservedDate)
Also you are executing the sproc twice - once using ExecuteNonQuery and once using ExecuteReader You should either return a value and use ExecuteNonQuery, creating a parameter to store the return value, or use ExecuteScalar to quickly pull the first result from the dataset.
I would suggest reading up more on basic SQL and how to execute queries with .NET.

You are not returning the COUNT.
Declare a variable, initialize it with the result and return it from the procedure:
ALTER PROCEDURE dbo.CountCottages
(
#CottageType nvarchar(50),
#ReservedDate datetime
)
AS
BEGIN
DECLARE #NumCottages int
SELECT #NumCottages = count(dbo.Cottages.CottageName)
FROM dbo.Cottages INNER JOIN
dbo.ResortTransactions ON dbo.Cottages.CottageID = dbo.ResortTransactions.CottageID
where dbo.Cottages.CottageType=#CottageType and dbo.ResortTransactions.Status != 'Cancelled' and dbo.ResortTransactions.ReservedDate != #ReservedDate
RETURN #NumCottages
END
Then use SqlCommand.ExecuteScalar instead of ExecuteNonQuery to get the value.

Cmd.ExeceuteNonQuery() is normally used to execute a procedure without expecting a result back.
But here you are looking for a scalar value.So Change it to cmd.ExecuteScalar().Also return the count back from the procedure.

I'll make a few assumptions - just a small tip whilst playing with this I would create a "scratch pad" in a SQL query and use table variables to test with as you can see below:
DECLARE #Cottages AS TABLE
(
Cottage_PK INT IDENTITY(1, 1) ,
CottageName VARCHAR(100) ,
CottageType VARCHAR(100)
)
DECLARE #Reservations AS TABLE
(
Reservation_PK INT IDENTITY(1, 1) ,
Cottage_FK INT ,
CheckinDate DATETIME ,
DepatureDate DATETIME ,
IsCanceled BIT
)
DECLARE #DateToCheck AS DATETIME ,
#CottageType AS VARCHAR(100)
SET #DateToCheck = '2012-09-15'
SET #CottageType = 'Some Type'
INSERT INTO #Cottages
( CottageName, CottageType )
VALUES ( 'CottageA', 'Some Type' )
INSERT INTO #Reservations
( Cottage_FK ,
CheckinDate ,
DepatureDate ,
[Status]
)
VALUES ( 1 , -- Cottage_FK - int
'2012-09-16' , -- CheckinDate - datetime
'2012-09-24' , -- DepatureDate - datetime
''
)
Now I took the assumption that if you want to check cottages availible on a date you would need to check in accordance to the checkin date and the depature date which results in using a between statement.
SELECT COUNT(c.CottageName) AS 'Cottages availible'
FROM #Cottages c
INNER JOIN #Reservations r ON c.Cottage_PK = r.Cottage_FK
WHERE NOT #DateToCheck BETWEEN r.CheckinDate
AND r.DepatureDate
AND c.[status] != 'Cancelled'
AND c.CottageType = #CottageType
Use this for testing - I passed a date within the range it it returned 0 and out of the range and it returned 1. Once your happy move this to your stored procedure.
CREATE PROCEDURE dbo.CountCottages
#DateToCheck DATETIME ,
#CottageType VARCHAR(100)
AS
SELECT COUNT(c.CottageName) AS 'Cottages availible'
FROM Cottages c
INNER JOIN ResortTransactions r ON c.Cottage_PK = r.Cottage_FK
WHERE NOT #DateToCheck BETWEEN r.CheckinDate
AND r.DepatureDate
AND c.[status] != 'Cancelled'
AND c.CottageType = #CottageType

Related

MVC C# Count Records Based on Condition

I am trying to count and display the number of logs conducted by various users from the Admin section.
Each user has a UserID and through this, I would like to count and display data from a specific table.
I have made of a stored procedure and passed it to the Controller via a ViewBag but it keeps returning 1 as the total for all values.
the procedure is Below
CREATE proc [Usp_GetCallCountByUserID]
#UserID int output
AS
BEGIN
SELECT COUNT (*) FROM Customer Where UserID= #UserID
GROUP BY UserID
set #UserID =##ROWCOUNT
END
GO
Controller:
public ActionResult Index()
{
con.Open();
SqlCommand comm = new SqlCommand("Usp_GetCallCountByUserID", con);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#UserID", SqlDbType.Int).Direction =
ParameterDirection.Output;
SqlDataReader reader;
reader = comm.ExecuteReader();
reader.Close();
ViewBag.CountLog = comm.Parameters["#UserID"].Value.ToString();
con.Close();
var callCustomers = db.Registrations;
return View(callCustomers.ToList());
}
Edit: answer edited after clarification
If I'm right you would do something like this:
CREATE proc [Usp_GetCallCountByUserID]
#UserId int
#TotalCount int output
AS
BEGIN
SELECT #TotalCount = COUNT(*) FROM Customer WHERE UserId = #UserId
END
Please modify calling c# code accordingly. You do not need the GROUP BY clause, if grouping by the same field you are filtering on.
Consideration: IMO a stored procedure is overkill for such a simple task, and does not give any sensible performance improvements, expecially if your application and DB server are always up (both will optimize the query execution, if repeated). When queries are so simple, I'd rather execute a CommandType.Text DbCommand:
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Count(*) FROM Customer where UserId = #UserId";
cmd.Parameters.Add("#UserId", SqlDbType.Int).Value = currentUserId;
using (var reader = cmd.ExecuteReader())
{
reader.Read(); // Advance one record
ViewBag.CountLog = reader.GetInt32(0);
}
}
Finally, since you seem to be using some sort of ORM (Entity Framework?), why not just:
db.Customers.Count(c => c.UserId == currentUserId);
That is pretty much equivalent to the code above.
First of all your stored procedure does exactly as expected, since ##ROWCOUNT returns the number of rows in the result.
You have to write your result in another variable like shown below.
For your Stored Procedure
DECLARE #Result INT
SELECT #Result = COUNT (*) FROM Customer Where UserID= #UserID
GROUP BY UserID
And then Read this value ;)
And Changes for your Code
reader.Close();
ViewBag.CountLog = comm.Parameters["#Result"].Value.ToString();
con.Close();
Don't use global variable ##ROWCOUNT
you have to save the value of COUNT(*) in your request, look code below,
CREATE proc [Usp_GetCallCountByUserID]
#UserID int,
#RowCount int output
AS
BEGIN
SELECT #RowCount = COUNT (*) FROM Customer Where UserID= #UserID
GROUP BY UserID
END
GO

Data Table Always getting empty

I am trying to display report in mvc web application using rdlc. I have created data set and data table. but now report viewer always reloading continuously. when i try to figure out the problem i found this issue.
Here C# Code
private DataTable GetData(DateTime sdate, DateTime edate,string user,string sp_name)
{
DataTable oDataTable = new DataTable();
string ConStr = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConStr))
{
SqlCommand cmd = new SqlCommand("GetBalanceSheet_CurrentUser", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#SDate", SqlDbType.DateTime).Value = sdate;
cmd.Parameters.Add("#EDate", SqlDbType.DateTime).Value = edate;
cmd.Parameters.Add("#Uid", SqlDbType.VarChar).Value = user;
SqlDataAdapter oSqlDataAdapter = new SqlDataAdapter(cmd);
oSqlDataAdapter.Fill(oDataTable);
}
return oDataTable;
}
Here Sql Stored Procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- GetBalanceSheet_CurrentUser '2017-09-12' ,'2017-11-12' ,'ab0eb318-de5f-4f13-a80b-7a95f678ad8a'
ALTER PROCEDURE [dbo].[GetBalanceSheet_CurrentUser]
#SDate DateTime,#EDate DateTime,#Uid VarChar(MAX)
AS
IF OBJECT_ID ('tempdb..#TEMP1') IS NOT NULL
DROP TABLE #TEMP1
IF OBJECT_ID ('tempdb..#TEMP2') IS NOT NULL
DROP TABLE #TEMP2
DECLARE #UserId VarChar(MAX)
SELECT #UserId = #Uid
SELECT ROW_NUMBER() OVER(ORDER BY Date) RNo,Description,Date,Amount,ForUser,CreatedUser,Status,ApprovedBy
INTO #TEMP1
FROM (
SELECT PEDM.ProjectExpenditureDescription AS Description , PEDM.ExpendedDate As Date,PEDM.ProjectExpenditureCost As Amount, ANU1.UserName As ForUser,ANU1.UserName As CreatedUser,PEDM.ApprovedStatus As Status,ANU2.UserName As ApprovedBy
FROM ProjectExpenditureDetailsModel PEDM
JOIN AspNetUsers ANU1
ON ANU1.Id = PEDM.CreatedUser
JOIN AspNetUsers ANU2
ON ANU2.Id = PEDM.ApprovedBy
WHERE PEDM.IsActive = 1
AND PEDM.IsDelete = 0
AND PEDM.Rejected = 0
AND PEDM.CreatedUser = #UserId
UNION ALL
SELECT OMDM.ObtainedMoneyDescription As Description,OMDM.ObtainedDate As Date,(OMDm.ObtainedMoneyAmount *-1) As Amount, ANU3.UserName As ForUser,ANU4.UserName As CreatedUser,OMDM.ApprovedStatus,ANU5.UserName As ApprovedBy
FROM ObtainedMoneyDetailsModel OMDM
JOIN AspNetUsers ANU3
ON ANU3.Id = OMDM.ForUser
JOIN AspNetUsers ANU4
ON ANU4.Id = OMDM.CreatedUser
JOIN AspNetUsers ANU5
ON ANU5.Id = OMDM.ApprovedBy
WHERE OMDM.IsActive = 1
AND OMDM.IsDelete = 0
AND OMDM.Rejected = 0
AND OMDM.ForUser = #UserId
)A
ORDER BY Date
SELECT RNo,Description,Convert (varchar(20),Date,103) AS ConvertedDate,Date,Amount,SUM(Amount) OVER (ORDER BY RNo) AS Balance,ForUser,CreatedUser,Status,ApprovedBy
INTO #TEMP2
FROM #TEMP1
SELECT RNo,Description,ConvertedDate,Date,Amount,Balance,ForUser,CreatedUser,Status,ApprovedBy
FROM #TEMP2
WHERE Date Between #SDate AND #EDate
When I execute program sql profiler indicates it hits successfully. but when i return result to data table its always getting empty.
I have executed sp manually using same parameters. it is showing 10
records.but when i call through my c# code its hitting but sql data
adapter always empty like {}
Do you execute your sp manually under the same account?
Your procedure uses datetime parameters but the literals for this parameters that you are passing in are language dependent.
Instead, you should pass them in language independent format yyyymmdd (without any separator)
Now, your login language is different from the default login of your application, this cause the date literals to be interpreted differently.
Here is an example to show you the problem. First execute it as it is, then comment set language us_english and uncomment set language British;
declare #t table (dt datetime);
insert into #t values ('20171001'), ('20171101'); -- added 1st oct + 1st nov
--set language British;
set language us_english;
declare #SDate datetime ='2017-09-12', #EDate datetime = '2017-11-12';
select *
from #t
WHERE dt Between #SDate AND #EDate;

Stored procedure doesn't return an int value

MySql Procedure Code:
CREATE DEFINER=`root`#`localhost` PROCEDURE `USP_CreateCliente`(IN nome_cliente VARCHAR(45))
BEGIN
Select 20;
INSERT INTO clienti ( nome_cliente )
VALUES ( nome_cliente );
Select id_cliente from clienti;
END
C# code in the controller page:
ClienteInfo CI = new ClienteInfo();
DboUser objdbo = new DboUser();
int id_cliente = 0;
CI.nome_cliente = txtNomeCliente.Text;
id_cliente = objdbo.CreateClienteInfo(CI);
DboUser class:
public int CreateClienteInfo(ClienteInfo CI)
{
int result;
MySqlConnection conn = new MySqlConnection();
DbConnection db = new DbConnection();
conn = db.ConnessioneDb();
MySqlCommand cmd = new MySqlCommand(Costanti.StoredProcedures.USP_CreateCliente, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#nome_cliente", CI.nome_cliente);
result = cmd.ExecuteNonQuery();
conn.Close();
return result;
}
I want my C# code to retrieve the id of my customer after inserting it into the database, so I can save it to the session and retrieve it again later in a page that will print a document with the customer's informations.
My id_cliente returns 0, do you notice any syntax error?
Did I do something wrong?
I'm 90% sure it's a problem dealing with the stored precedure tough, cause the customer is inserted correctly
Change this line
result = cmd.ExecuteNonQuery();
to
result = Convert.ToInt32(cmd.ExecuteScalar());
but you should also change your stored procedure because it doesn't return the last id generated for you by the AUTO_INCREMENT column id_cliente
CREATE DEFINER=`root`#`localhost` PROCEDURE `USP_CreateCliente`(IN nome_cliente VARCHAR(45))
BEGIN
INSERT INTO clienti ( nome_cliente ) VALUES ( nome_cliente );
Select LAST_INSERT_ID();
END
In MySql, to get the generated auto_increment value, you could use LAST_INSERT_ID(), next, your C# code don't need to use ExecuteNonQuery, which returns just the number of rows that you have changed, added or deleted, but you use ExecuteScalar which returns the first column of the first row of the last SELECT command executed by your stored procedure. (It is the SELECT LAST_INSERT_ID())
Also, to complete the answer, you don't really need a stored procedure for this kind of simple work. The advantages should be minimal while the problems related to a different piece of software to maintain are self evident.
Your C# code could be (removed the usage of your DbConnection class because it is not clear what it does)
public int CreateClienteInfo(ClienteInfo CI)
{
int result;
string cmdText = #"INSERT INTO clienti ( nome_cliente ) VALUES ( nome_cliente );
Select LAST_INSERT_ID();";
using(MySqlConnection conn = new MySqlConnection(....connectionstring .....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, conn);
{
conn.Open()
cmd.Parameters.AddWithValue("#nome_cliente", CI.nome_cliente);
result = Convert.ToInt32(cmd.ExecuteScalar())
return result;
}
}
Here you use the possibility to pass batch commands to your MySql engine, meaning two commandtexts with the same MySqlCommand separating them with the semicolon

Insert 10000 records from C# into SQL Server

I have a C# console program
Selects 10000 records from Input table (Keyid varchar(4), Address varchar(100), Name varchar(100)).
for each record from Input table, it calls an API that returns data (if person works in that address, status is OK else NOT OK, also returns address type-place of interest or residential, commercial etc.) that needs to be saved in one main table and a detail table.
Main table:
1001|JOE STILTON| 2 MAIN ST, SALEM,PA| OK|4/15/2014
Detail table:
1001|PHARMACY
1001|COMMERCIAL
i.e Joe works in a pharmacy which is also a commercial bldg.
Right now, I call the API. then I call a method,
private static void insertTable(string keyid, DateTime updDate, string name, string address,string status)
{
Int32 rowsAffected = 0;
string connectionString = GetConnectionString();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand("google.usp_InsertCompanyAddrComponents", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 90;
cmd.Parameters.Add("#keyid", SqlDbType.VarChar);
cmd.Parameters["#keyid"].Value = keyid;
cmd.Parameters.Add( new SqlParameter("#dateverified", updDate));
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = name;
cmd.Parameters.Add("#address", SqlDbType.VarChar);
cmd.Parameters["#address"].Value = address;
cmd.Parameters.Add( new SqlParameter("#status", status));
try
{
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
connection.Close();
}
Then, I call another similar method that inserts into detail table.
Since I have to do this for 10,000 records at a time, there is lot of I/O. how can I change to do batch insert? all 10000 insert at a time?
Thanks
R
You can also take a look into table types in SQL Server. You can pass two table types in stored procedure and do required operations directly over there.
Here is my sample stored proc
CREATE PROCEDURE [dbo].[usp_AssociateTags]
#Tags AS UDT_Tag READONLY
AS
SET XACT_ABORT ON
BEGIN TRAN
--Insert into Tag Master
INSERT INTO dbo.TagMaster
(
Name
,IsActive
)
VALUES ( '', -- Name - varchar(50)
1 -- IsActive - bit
)
DECLARE #TagId AS INT
SET #TagId=SCOPE_IDENTITY()
INSERT INTO dbo.TagCollection
( TagNumber, TagId )
SELECT TagNumber, #TagId FROM #Tags t
WHERE NOT EXISTS(SELECT * FROM dbo.TagCollection WHERE TagNumber = t.TagNumber)
COMMIT TRAN
SET XACT_ABORT OFF
Script to test this stored procedure
--DECLARE #hello as UDT_Tag
--INSERT INTO #hello VALUES('vaibhav')
--INSERT INTO #hello VALUES('Shantanu')
--INSERT INTO #hello VALUES('Sam')
--INSERT INTO #hello VALUES('Aakash')
--EXEC usp_AssociateTags #hello
--SELECT * FROM dbo.TagCollection
C# code to consume this procedure
SqlParameter Tags = new SqlParameter { ParameterName = "#Tags"
, Value = entity.Tags.ToDataTable()
, Direction = ParameterDirection.Input
, SqlDbType = SqlDbType.Structured, TypeName="UDT_Tag" };
SqlHelper.ExecuteNonQuery(tran, CommandType.StoredProcedure
, "usp_AssociateTags", Tags);
CodeProject

SQL Server IF..ELSE do not show at Windows Application

I have this stored procedure:
exec sp_Defect_B '2013-05-20 00:00:00','2013-05-25 23:59:59'
Which has a IF..ELSE to execute different thing depends on the code given:
alter proc [dbo].[p_Defect_B] (#dtFrom datetime, #dtTo datetime)
as
begin
DECLARE #Total TABLE
(
[No] int, TSampel float
)
-- Total
insert into #Total
select 1 as [No], SUM(H.Total) as TSampel from TrxDBHHDr HH
left join TrxDBHdr H on HH.DBNO=H.DBNO
left join ProductType PT on H.ACd=PT.ACd and PT.GCd=1
where HH.Deleted=0 and HH.DBDate between #dtFrom and #dtTo
DECLARE #Defect TABLE
(
DefectCd varchar(15),Name varchar(50), Defect float
)
-- Defect
insert into #Defect
select D.DefectCd,DB.Name,sum(coalesce(D.Qty,0)) as Defect from TrxDBHHDr HH
left join TrxDBDtl D on HH.DBNO=D.DBNO
left join ProductType PT on D.acd=PT.ACd and PT.GCd=1
left join DefectBK DB on DB.DefectCd=D.DefectCd
where HH.Deleted=0 and HH.DBDate between #dtFrom and #dtTo
group by D.DefectCd,DB.Name
DECLARE #SubTotal TABLE
(
Name varchar(50), Defect float, TSampel float, PDefect float
)
insert into #SubTotal
select D.Name,D.Defect,T.TSampel,D.Defect*100/T.TSampel as PDefect from #Defect D
left join #Total T on T.[No]=1
order by PDefect desc
DECLARE #TotalD TABLE
(
[No] int,Defect float
)
insert into #TotalD
select 1, Sum(D.Defect) as Defect from #Defect D
insert into #SubTotal
select 'Total Defect', D.Defect, T.TSampel, D.Defect*100/T.TSampel as PDefect from #TotalD D
left join #Total T on T.[No]=1
select * from #SubTotal
end
I execute the code in SSMS and it worked perfectly. But when I try to use the code in C# Windows application it doesn't get any value.... How is that possible? Did I miss anything?
Only this stored procedure didn't return table value....
I tried using temp table, table variable, they still didn't return table value...
This is the C# Code:
sql= "exec p_Defect_B '2013-05-20 00:00:00','2013-05-25 23:59:59'";
RunQuery qu_data = new RunQuery();
DataTable data = new DataTable();
data = qu_data.OpenAdoQuery(sql,"IP")
This is part of my program of my connection C# to SQL Server
myCon = new OleDbConnection(strCon);
DataTable myData = new DataTable();
myCon.Open();
OleDbDataAdapter myOleAdapter = new OleDbDataAdapter();
myOleAdapter.SelectCommand = new OleDbCommand(sql,myCon);
myOleAdapter.Fill(myData);
myCon.Close();
All the tables return value in SMSS.
All table variable show result in SMSS.
The result didn't show on C# Windows Application using ADOAdapter.
I tried using Temp Table and Table Variable, didn't work.
I tried not using IF..ELSE, didn't work.
You should really use the SqlConnection then connecting to SQL Server - and you should execute your stored procedure using a standard SqlCommand - don't use the EXEC.... code.
Try this code:
// setup connection and command
using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand cmd = new SqlCommand("dbo.p_Defect_B", conn))
{
// define command as stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// define and set parameter values
cmd.Parameters.Add("#dtFrom", SqlDbType.DateTime).Value = new DateTime(2013, 5, 20);
cmd.Parameters.Add("#dtFrom", SqlDbType.DateTime).Value = new DateTime(2013, 5, 25, 23, 59, 59);
// execute your query
conn.Open();
// get a data reader to read the values from the result set
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// iterate over the result set
while (rdr.Read())
{
// fetch the values - depends on your result set - YOU NEED TO ADAPT THIS!
var value1 = rdr.GetInt(0);
var value2 = rdr.GetString(1);
......
}
rdr.Close();
}
conn.Close();
}

Categories