SQL Server IF..ELSE do not show at Windows Application - c#

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

Related

How should I get the values from the select query of the stored procedure in c#

I want the date and the name from the select query which if I run as normal query I get the results but i when I try to get the results in C# all I get is count=0. Can anyone tell me what wrong am I doing?
Here is the C# code
private List<CertificationSummary> GetLastAccessData (string taskOwner)
{
List<CertificationSummary> lastAccessedResult = new List<CertificationSummary>();
string connectionString = SqlPlusHelper.GetConnectionStringByName("MetricRepositoryDefault");
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlParameter[] sqlParams = new SqlParameter[1];
sqlParams[0] = new SqlParameter("#taskOwner", SqlDbType.NVarChar);
sqlParams[0].Value = taskOwner;
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetLastAccessedCertificationData";
cmd.Parameters.AddRange(sqlParams);
cmd.ExecuteNonQuery();
}
return lastAccessedResult;
}
And here is the stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetLastAccessedCertificationData]
(#taskOwner nvarchar(255))
AS
BEGIN
DECLARE #name nvarchar(100)
DECLARE #lastAccessedDate [datetime]
SELECT #name = Name
FROM CertificationReviewCycles
INNER JOIN UserReviewCycleAccess ON CertificationReviewCycles.CertificationReviewCycleID = UserReviewCycleAccess.LastAccessedReviewCycleID
WHERE USERID = #taskOwner
SELECT #lastAccessedDate = LastAccessedDate
FROM UserReviewCycleAccess
WHERE UserID = #taskOwner
CREATE TABLE #tempTable
(
name [nvarchar](255) NULL,
[LastAccessedDate] [datetime] NULL,
)
INSERT INTO #tempTable VALUES (#name, #lastAccessedDate)
SELECT TOP(1) name, LastAccessedDate
FROM #tempTable
END
GO
You are returning lastAccessedResult which is has just been set to new List<CertificationSummary>(). This list has no items, so it has a count of 0.
Use ExecuteReader instead of ExecuteNonQuery and you can then read the data returned and store them into your lastAccessedResult list.
Read here for more info.
ExecuteNonQuery will not return results, and should only be used when you don't expect rows back. This is common for UPDATE statements.
Since you're interested in reading the rows returned by the stored procedure, use ExecuteReader, e.g var reader = cmd.ExecuteReader();
See here for more:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader?view=dotnet-plat-ext-3.1
You're using ExecuteNonQuery, which discards any grids from the query. You need to use ExecuteReader to consume grids, but it is a lot of mess and ceremony - the API is verbose. Frankly, I'd recommend a tool like "Dapper" (freely available on NuGet), then this becomes just
private List<CertificationSummary> GetLastAccessData (string taskOwner)
{
string connectionString = SqlPlusHelper.GetConnectionStringByName("MetricRepositoryDefault");
using var connection = new SqlConnection(connectionString);
return connection.Query<CertificationSummary>(
"GetLastAccessedCertificationData",
new { taskOwner }, // <== parameters
commandType: CommandType.StoredProcedure).AsList();
}

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;

Return multiple datasets from sql server stored procedure

I need to return through Web Api a Base64 XML output based upon calling a stored procedures which runs 5 different queries.
Stored procedure is not written ( I need to write it ) but there are 5 queries in which the data is completely different tables and columns etc... so I am wondering if this is even possible?
I know in Oracle you can return multiple cursors, but with SQL Server , can I return into asp.net 4.5 ( mvc c# / Ado.net) multiple datasets or collections? Any examples of this?
Example of just ONE of the queries
-- Content Tab
SELECT -- vTC.[TemplateId]
t.Name as "Client Name and Document" ,vTC.[SectionName] ,vTC.[ContentId] ,vTC.[ContentName]
,vTC.[ContentDescription],vTC.[ContentValue] ,CAL.ContentValue as "Spanish Content" , iif(S.IsClientSection = 1, 'Global Section','Template Section') as "Global or Template Section"
,DT.Title as DataType ,iif(vTC.IsRequired = 1, 'Yes', 'No') as "Required" ,vTC.[DisplayType]
FROM [dbo].[vwTemplateContent] vTC
left join dbo.Template t on vTC.TemplateId = t.TemplateId
left join dbo.DataType DT on vTC.DataTypeId = dt.datatypeid
left join dbo.Section S on S.SectionID = vTC.SectionID
left join [dbo].[ContentAlternateLanguage] CAL on vTC.ContentId = CAL.ContentID
where vTC.templateid in (1)
order by DisplayOrder
If you are going to get multiple tables then you have to write multiple select statements into your stored procedure like below:
CREATE PROCEDURE SPName
(
/*Declare your parameters*/
#parm1 dataType
)
AS
BEGIN
/*Write your select statements below*/
-- SELECT * FROM tblName
-- SELECT * FROM tblName2
END
You have to fill these records into your DataSet, DataSet supports multiple table into ADO.net.
Please refer below code to fill your DataSet:
SqlConnection con=new SqlConnection("YourConnection String");
SqlCommand cmd=new SqlCommand();
SqlDataAdapter da=new SqlDataAdapter();
DataSet ds = new DataSet();
cmd = new SqlCommand("SPName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#parm1", id);//if you have parameters.
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
After this you can take advantage of different multiple recordsets using
ds.Tables[0]
ds.Tables[1]
..
Hope it will helps you
Thanks
Here's a basic example:
SQL Proc:
CREATE PROCEDURE usp_getStudentsAndClasses
#ClassName varchar(50)
, #IsActive bit
AS
BEGIN
--First select is first table
SELECT *
FROM Students
--Second select is second table, etc.
SELECT *
FROM Classes
--Third table...
--Can be more complex, as long as there is a result set
SELECT s.FirstName
, s.LastName
FROM Students s
JOIN StudentSeating ss
ON s.StudentID = ss.StudentID
JOIN Classes c
ON c.ClassID = ss.ClassID
WHERE s.IsActive = #IsActive
AND c.Name = #ClassName
END
C# function:
public DataSet GetDataSet(SqlConnection connection, string storedProcName, params SqlParameter[] parameters)
{
var command = new SqlCommand(storedProcName, connection) { CommandType = CommandType.StoredProcedure };
command.Parameters.AddRange(parameters);
var result = new DataSet();
var dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(result);
return result;
}
C# usage:
var connection = new SqlConnection("Your_connection_string");
var parameters = new SqlParameter[]
{
new SqlParameter("ClassName", "Robotics"), //example of string value
new SqlParameter("IsActive", true) //example of numeric value
};
var dataSet = GetDataSet(connection, "usp_getStudentsAndClasses", parameters);
var firstTable = dataSet?.Tables?[0]; //use as any other data table...
Notice, it is almost the same code as you would use for a single-table stored procedure, except the data type returned is a DataSet, not a DataTable. A DataSet contains a DataTableCollection More info on MSDN
Yes, It is possible. You just need to write your select queries and you will get the data in a DataSet. If you have a single select query, you will get DataTable and if you have number of select queries (Say 5), then you will get a DataSet that has 5 DataTables. It is so simple. Just write your procedure and have fun.
Edit:
Example of Stored Procedure (pseudo code) is given below:
create Proc Name_Of_Proc
(
#FirstParam DataType,
#SecondParam DataType
)
AS
Begin
Select statement 1
Select statement 2
Select statement 3 --and so on upto n.
end
You need to do this in your database. After doing this, you need to execute this procedure from c# by using ADO.NET. You need to use SqlConnection SqlCommand and SqlDataReader object to do this. You can search on google or SO itself for more examples. One such link on SO is How to execute Stored procedure in c#

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

Is it possible to query records obtained from extended stored procedures from TSQL in C#?

So this is the code I have tried, in C#, which failed to give me the result I needed.
SqlCommand comm = new SqlCommand("exec sys.xp_readerrorlog 0,1,'','',#StartDate,#EndDate,N'Desc'");, conn);
comm.Parameters.AddWithValue("#StartDate", "");
comm.Parameters.AddWithValue("#EndDate", "");
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr.GetString(0));
}
Basically, I need to extract data from these logs (which gets pulled from the SQL Server through this stored procedure), and it seems that When I use a dataReader, there are no records, and if I use a dataset with data adapter, there are also no tables/records in the dataset. This information is critical for me to query.
Is there a way that I can still query the SQL Server error logs without having to resort to stored procedures?
ANOTHER UPDATE:
The parameters for this extended stored procedures are:
Value of error log file you want to read: 0 = current, 1 = Archive, 2 = etc...
Log file type: 1 or NULL = error log, 2 = SQL Agent log
Search string 1: String one you want to search for
Search string 2: String two you want to search for to further refine
the results
Search from start time
Search to end time
Sort order for results: N'asc' = ascending, N'desc' = descending
Another method I tried
SqlCommand comm = new SqlCommand(#"exec sys.xp_readerrorlog 0,1,'','',null,null,N'Desc'", conn);
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
Console.WriteLine(ds.Tables.Count); //0 returned: no data in dataset
If i was allowed to use stored procedures to query the data, I could have used this following extract, but it would have been deployed too much and be a pain to maintain and decommission
IF (EXISTS( SELECT * FROM sys.procedures where name = 'writelogs' ))
BEGIN
DROP PROCEDURE Writelogs;
END
GO
CREATE PROCEDURE WriteLogs #Servername varchar(40),#InstanceName varchar(40),#Pattern varchar(max),#ParamBeginDate varchar(40), #ParamEndDate varchar(40) AS
BEGIN
DECLARE #BeginDate DateTime
DECLARE #EndDate DateTime
DECLARE #NextQueryID int
--First we have to convert the timestamps EndDate and BeginDate to something usable
IF (#ParamBeginDate = 'Beginning')
BEGIN
SET #BeginDate = null; --null will cause sys.xp_readerrorlog to read from beginning
END
ELSE IF (#ParamBeginDate = 'Last')
BEGIN
SELECT TOP 1 #BeginDate = L.TimeLogged FROM LogTable L ORDER BY L.TimeLogged Desc
END
ELSE
BEGIN
BEGIN TRY
SET #BeginDate = CAST(#ParamBeginDate AS DATETIME);
END TRY
BEGIN CATCH
SET #BeginDate = null;
END CATCH
END
IF (#ParamEndDate = 'Now')
BEGIN
SET #EndDate = GETDATE(); --null will cause sys.xp_readerrorlog to read till now
END
ELSE
BEGIN
BEGIN TRY
SET #EndDate = CAST(#ParamEndDate AS DATETIME);
END TRY
BEGIN CATCH
SET #EndDate = GETDATE();
END CATCH
END
--Temporary Table to store the logs in the format it is originally written in
CREATE TABLE TMP
(LogDate DateTime2
,Processinfo varchar(40)
,[Text] varchar(max))
--truncate the milliseconds (else ALL records will be retrieved)
SET #EndDate= dateadd(millisecond, -datepart(millisecond, #EndDate),#EndDate);
SET #BeginDate= dateadd(millisecond, -datepart(millisecond, #BeginDate),#BeginDate);
INSERT INTO TMP exec sys.xp_readerrorlog 0,1,'','',#BeginDate,#EndDate,N'DESC';
SELECT TOP 1 L.TimeLogged FROM LogTable L ORDER BY L.Timelogged desc
INSERT INTO LogTable
SELECT #Servername,#InstanceName,T.[text],T.LogDate,GETDATE(),0,0,null,#NextQueryID FROM TMP t WHERE PATINDEX(#Pattern,t.[Text]) > 0;
DROP TABLE TMP;
END
You can't use AddWithValue for the dates.
If the dates are blank, then you need to pass null as the value, not an empty string. Those have completely different meanings.
To test, open Management Studio and execute the following:
exec sys.xp_readerrorlog 0,1, '', '', '', ''
That will have zero results. However if you do this:
exec sys.xp_readerrorlog 0,1, '', '', null, null
You will get back a lot of records.
BTW, your update is still wrong. The dataset code you have will never do anything. Change it to:
SqlCommand comm = new SqlCommand(#"exec sys.xp_readerrorlog 0,1,'','',null,null,N'Desc'", conn);
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds, "sometablename");
Console.WriteLine(ds.Tables.Count); //0 returned: no data in dataset
Note the fill command...

Categories