Outputting stored procedure results - c#

Apologies if this is somewhat of an elementary question... .net newb here thrown in at the deep end.
I have created a stored procedure to return a record which I am executing as below. When I inspect "r" with a breakpoint in Visual Studio express, my data is returned correctly.
MyPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
var dd = dealerDetails();
}
protected DataTable dealerDetails()
{
SqlConnection cn;
SqlCommand cmd;
using (cn = new SqlConnection(Settings.Server.ConnectionString))
{
cn.Open();
cmd = new SqlCommand("spMyStoredProcedure", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#strslug", SqlDbType.NVarChar, -1).Value = Page.Request.QueryString["_slug"];
JJ.Diagnostics.Tracer.Trace(cmd);
try
{
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
??????
}
r.Close();
return ?????;
}
catch (SqlException exSql)
{
// Make an event log entry of the exception
EventLogController.LogException(exSql);
throw;
}
catch (Exception ex)
{
// Make an event log entry of the exception
EventLogController.LogException(ex);
throw;
}
}
}
When I simply try to return r, I get an error:
Cannot inplicityly convert type 'System.Data.IDataReader' to 'System.Data.DataTable'.
An explicity conversion exists (are you missing a cast?)
I would like to be able to access the results from this stored procedure in MyPage.aspx. I'd assume that I could do this with <%=dd.propname%> am I correct in this or would it require any additional steps?
Please let me know if I've ommited any important information here.

Use a data adapter to fill a data table and return that. If your stored procedure is returning only the data that is required. I don't see any reason to iterate through every column and explicitly define them. A SqlDataAdapter will fill a DataTable for you without hard coding and adding the row values.
HERE is some reading and examples of SqlDataAdapters.
using (SqlDataAdapter da = new SqlDataAdapter(cmd, cn)
{
DataTable dt = new DataTable("TableName");
da.Fill(dt);
return dt;
}
Entire Code:
// Utilize the using directive on any disposable objects so you aren't
// left with garbage.
using (SqlConnection cn = new SqlConnection(Settings.Server.ConnectionString))
using (SqlCommand cmd = new SqlCommand("spMyStoredProcedure", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
// define your parameter here, just personal preference, but makes debugging
//easier in my opinion.
string slug = Page.Request.QueryString["_slug"];
// Use the newer .AddWithValue command.
cmd.Parameters.AddWithValue("#strslug", slug);
JJ.Diagnostics.Tracer.Trace(cmd);
try
{
// SqlDataAdapter will automatically open/close your connection for you,
// however, for future reference, try to open your connection only when
// it is required to be opened. This will reduce your connection time/
// server strain.
// cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd, cn)
{
// Data adapter will automatically fill your returned data table.
DataTable dt = new DataTable("TableName");
da.Fill(dt);
return dt;
}
}
catch (SqlException exSql)
{
// Make an event log entry of the exception
EventLogController.LogException(exSql);
throw;
}
catch (Exception ex)
{
// Make an event log entry of the exception
EventLogController.LogException(ex);
throw;
}
}
From this point you may access your data like this:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dd = dealerDetails();
// if more than one row is expected you can use the for loop
// if not, just access them directly.
for (int i = 0; i < d.Rows.Count - 1; i++)
{
// Jump straight to here if you are positive you will only
// return 1 row of data.
string ColumnName1 = dd.Rows[i]["ColumnName1"].ToString();
string ColumnName2 = dd.Rows[i]["ColumnName2"].ToString();
}
}

According to your dealerDetails method signature - return value is DataTable. So you can't return DataReader because it is not derived from DataTable.
You need to create DataTable and its columns, and fill table while reading from dataReader.
Something like this
using(var r = cmd.ExecuteReader())
{
var dt = new DataTable();
dt.Columns.Add("Column1_Name", typeof(column1_Type));
dt.Columns.Add("Column2_Name", typeof(column2_Type));
while (r.Read())
{
var dro = dt.NewRow();
dro["Column1_Name"] = somevalue_from_reader;
dro["Column2_Name"] = somevalue_from_reader;
dt.Rows.Add(dro);
}
r.Close();
return dt;
}

Related

how can I fill a data table variable value from class response in c#

How can I pass retrieve class variable value to the checkIn form?
checkIn form: my question is: why is the oldCheckInDt variable still empty?
// assign variable
DataTable oldCheckInDt = new DataTable();
private void btnUpdateCheckIn_Click(object sender, EventArgs e)
{
Retrieve.loadDataTable("sp_loadBasicCheckIn", oldCheckInDt, Convert.ToInt32(txtCheckInId.Text.Trim()));
// my question - why is "oldCheckInDt"// still empty
}
Retrieve class:
public static void loadDataTable(string proc, DataTable tb, Int32 Id)
{
try
{
SqlCommand cmd = new SqlCommand(proc, MainClass.con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", Id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
tb = dt; // tb successfully filled with data.
}
else
{
tb = null;
}
}
catch (Exception ex)
{
MainClass.showMessage("Exception : " + ex, "error");
}
}
When you pass a DataTable in that way, the receiving method creates a new variable (called tb) in its stack and assign at that variable the reference to the memory where the line DataTable oldCheckInDt = new DataTable(); created the initial table.
Now when you write tb = dt; you are changing the value of tb (it contains a reference) to a different reference (the value of dt) but the initial oldCheckInDt is unaffected by this operation. It still contains the original reference.
This is key point in programming. Understanding the difference between values and references is fundamental See: Values vs Reference and many more articles about this point.
However, to fast fix your code I think you should return the DataTable loaded in the loadDataTable method instead of trying to assign the loaded table to a parameter passed from the caller.
public static DataTable loadDataTable(string proc, Int32 Id)
{
try
{
using(SqlConnection con = new SqlConnection(MainClass.Connectionstring))
{
con.Open();
SqlCommand cmd = new SqlCommand(proc, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = Id;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
catch (Exception ex)
{
MainClass.showMessage("Exception : " + ex, "error");
return null;
}
}
Then in the calling code you could write
// assign variable
DataTable oldCheckInDt = new DataTable();
private void btnUpdateCheckIn_Click(object sender, EventArgs e)
{
oldCheckInDt ? Retrieve.loadDataTable("sp_loadBasicCheckIn", oldCheckInDt, Convert.ToInt32(txtCheckInId.Text.Trim()));
if(oldCheckInDt!= null && oldCheckInDt.Rows.Count > 0)
{
....
}
else
{
....
}
}
Notice other changes made to the loadDataTable method. First of all is a common error to use a global connection object and keep it open for the lifetime of an application. Create/Use/Destroy is the best way to preserve resources and let the ADO.NET Connection Pooling do its dirty work for you to serve connections. Second, do not use AddWithValue because it has a subtle behavior with parameters of type Date, Decimals/Float or event strings. Better avoid it

How to get values from table valued function in C#

I have a program where i have to display
The Event Description (OpisDogodka)
Location (Lokacija)
Time (ura)
My table valued function:
[dbo].[DobiDogodek](
#Ime nvarchar(100), #Datum date)
RETURNS TABLE AS RETURN (SELECT OpisDogodka AS 'Opisdogodka',Lokacija, Ura FROM Dogodek WHERE Ime=#Ime AND Datum=#Datum)
My method to connect to the server:
public string Dobi_dogodek(string ime,string datum)
{
string a="";
cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(#Ime,#Datum)",povezava); //povezava = connectio and it succeeds to connect to the server.
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Ime", ime);
cmd.Parameters.AddWithValue("#Datum", datum); //how to pass date only?
try
{
SqlDataReader Reader = cmd.ExecuteReader();
while(Reader.Read())
{
a = Reader.GetString(0)+" "+Reader.GetString(1)+" "+Reader.GetString(3).ToString(); // get what?
}
Uspeh = true;
}
catch (Exception e)
{
ex = e;
}
finally
{
povezava.Close();
}
return a;
}
I tried also using Datatable and datarow. I am also unsure how to work with Date. I know how to work with DateTime, but I need Date and Time separate. What I am doing wrong?
4.6.2017 (11.40 am CET)Update:
It seems I get the desired result
public List<string> Dobi_dogodek(string ime,string datum)
{
s = new List<string>();
cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(#Ime,#Datum)",povezava);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Ime", ime);
cmd.Parameters.AddWithValue("#Datum", Convert.ToDateTime(datum));
dt = new DataTable();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
try
{
foreach (DataRow dr in dt.Rows)
{
s.Add(dr["Opis dogodka"].ToString() + "\\" + dr["Lokacija"].ToString() + "\\" + dr["Ura"].ToString());
}
Uspeh = true;
}
catch (Exception e)
{
ex = e;
}
finally
{
povezava.Close();
}
return s;
}
Now I just need to split the strings according to my requirements, but is the a better (not necessarily an easy) way?
Try this:
cmd.Parameters.AddWithValue("#Datum", Convert.ToDateTime(datum));
See also https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx .
what is happening when you run it? are you getting an error message? is it getting it as an int? did you see what the sql server is getting from application by using sql profiler?
I will double check but I think your problem is you are not putting quotes around your variables in our statement so when it runs it is evaluating them as ints. try "SELECT * FROM dbo.DobiDogodek('#Ime','#Datum')". It been a long time since I havnt used something like EF...

One instance of class can't do two functions at the same time

I'm working on ASP.NET web aplication. I'm making it to be MVC and i have a problem with controler class. When i want to populate a drop down list with elements from my SQL database, class is working but only one instance of class with just one drop down list. When i use one class to populate 2 or more drop down lists it doesn't work and VS is not raising any errors. The controler class works, and it can populate drop down list, but just only one drop down list when page is loaded. So to work i have to make an instance of controler class for every drop down list. Please, can someone explain to me why won't work...
this is my DbBroker:
public DataTable VratiKategorije()
{
DataTable kategorije = new DataTable();
using (cn)
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM KategorijaLeka", cn);
adapter.Fill(kategorije);
}
catch (Exception err)
{
//
}
}
return kategorije;
}
And this is my Controler class which is using DbBroker:
public void VratiKategorije(DropDownList ddlKategorije){
try
{
ddlKategorije.DataSource = dbB.VratiKategorije();
ddlKategorije.DataTextField = "Naziv";
ddlKategorije.DataValueField = "ID_Kategorije";
ddlKategorije.DataBind();
}
catch (Exception err)
{
//Handle the err
}
ddlKategorije.Items.Insert(0, new ListItem("", ""));
}
And this is on Load_Page():
protected void Page_Load(object sender, EventArgs e)
{
KontrolerLeka kl = new KontrolerLeka();
kl.VratiKategorije(kategorijaLeka);
}
I found what was the problem. Ok, so when you use using() function with adapter there is no closing connection to database so when same function is called it can't populate another drop down list because the connection from last drop down list function is not closed. Insted of that code in DbBroker i used this and it worked! "pokreniDBtransakciju()" use cn (sql connection string) and after taking Record Set from database the connection is closed using "cn.Close()" which solved all problems.
DbBroker:
public DataTable Uzmi()
{
DataTable dt;
dt = new DataTable();
SqlCommand sc = new SqlCommand();
try
{
sc.CommandText = "SELECT * FROM KategorijaLeka";
sc.Connection = pokreniDBTransakciju();
SqlDataReader reader;
reader = sc.ExecuteReader();
dt.Load(reader);
cn.Close();
}
catch (SqlException e)
{
Console.WriteLine("GRESKA!!!" + e);
return null;
}
return dt;
}

C# Mysql multiple queries

Im trying to build up a little status-tool. I need to get results of multiple queries (about 4-5). The general connection-setup and 'how-to-read-data' is already done but I cant figure out how the another query executed.
Everything I found while searching for it is for the SqlClient. Im totally overcharged with this.
Here is my code so far (be patient, im a newbie to this):
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC";
try
{
conn.Open();
}
catch (Exception ex)
{
listView1.Items.Add("Error: " + ex);
}
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
listMember.Add(reader["fullname"].ToString());
listOnline.Add(reader["online"].ToString());
}
conn.Close();
// SQL ENDING //
// SET ENTRIES TO LISTVIEW //
int counter = 0;
foreach(string member in listMember)
{
ListViewItem item = new ListViewItem(new[] { member, listOnline.ElementAt(counter) });
item.ForeColor = Color.Green;
listView1.Items.Add(item);
counter++;
}
}
Im not really sure how the design/layout will look like in the end, so I would like to just append the results to lists in the sql-part to process the data later out of the lists.
Do I really have to setup a complete new connection after conn.Close()? Or is there any other way? I can just imagine: 5 queries with their own connection,try,catch and 2 loops... this will get about 100-200 lines just for getting the results out of 5 queries. Isnt that a bit too much for such an easy thing?
Hope for some help.
Greetings.
According to the new comments my latest code:
Top:
public partial class Form1 : Form
{
public static string connString = "Server=10****;Port=3306;Database=e****;Uid=e****;password=****;";
public Form1()
{
InitializeComponent();
MySqlConnection conn = new MySqlConnection(connString); // Error gone!
}
Body part:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
{
try
{
MySqlCommand cmd = conn.CreateCommand(); // ERROR: conn does not exist in the current context.
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
using (conn) // ERROR: conn does not exist in the current context.
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listMember,listOnline);
//...2nd query
//QueryTwoFields("your new Select Statement", otherList, otherList);
}
}
You don't have to close connection every time you execute one query rarher than close the sqlreader assigned to that connection. Finally when all of your queries have been executed you close the connection. Consider also the use of using:
You cal also define a method for execution your Query in order for your code not to be repetive:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
///Select into List S1 and List S2 from Database (2 fields)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
using (conn)
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listmember,listonline)
//...2nd query
QueryTwoFields("your new Select Statement",myOtherList1,myOtherlist2)
....
}
}
EDIT :
Take in mind you cant define QueryTwoFields method inside button handler. You must define it outside (see code above).
Also Define your connection data in the start of the programm:
namespace MyProject
{
/// <summary>
/// Defiine your connectionstring and connection
/// </summary>
///
public partial class Form1 : Form
{ public static string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
.........
Datatables are fantastic
Using a data table is a nice way to do both read and write. And it comes with the luxury of eveything you can do with a datatable - like asssigning it directly to a datagrid control, sorting, selecting and deleting while disconnected.
The sample below assumes a MySqlConnection conection property managed by calls to your own OpenConnection() and CloseConnection() methods not shown.
Simple datatable read demo:
public DataTable Select(string query = "")
{
//Typical sql: "SELECT * FROM motorparameter"
DataTable dt = new DataTable();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
dt.Load(dataReader);
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return data table
return dt;
}
else
{
return dt;
}
}
In case of writing back the datatable to the database - supply the SQL you used in the read (or would have used to read to the data table):
public void Save(DataTable dt, string DataTableSqlSelect)
{
//Typically "SELECT * FROM motorparameter"
string query = DataTableSqlSelect;
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand mySqlCmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = myCB.GetUpdateCommand();
adapter.Update(dt);
//close Connection
this.CloseConnection();
}
else
{
}
}
The neat thing the datatable is extremely flexible. You can run your own selects against the table once it contains data and before writing back you can set or reset what rows needs updating and by default the datatable keeps track of what rows you update in the table. Do not forget primary key column(s) for all tables in the db.
For multiple queries consider if possible using a join between the database tables or same table if data related or use a UNION sql syntax if column count and type of data is the same. You can allways "create" your extra column in the select to differ what data comes from what part of the UNION.
Also consider using CASE WHEN sql syntax to conditionally select data from different sources.

How to call a stored procedure using ADO.NET?

private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****";
conn.Open();
SqlCommand cmd = new SqlCommand();
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
//cmd.CommandText = "Select ChatRoomID=#ChatRoomID,ChatRoomName=#ChatRoomName from tblChatRoom";
//cmd.Connection = conn;
SqlDataAdapter adapt = new SqlDataAdapter("Chatroomapp",conn);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds=new DataSet();
DataTable dt = new DataTable();
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
adapt.Fill(ds, "tblChatRoom");
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
catch (Exception ex)
{
MessageBox.Show("Error", ex.Message);
}
}
While compiling the program I got only connection fails message box, in the database. I found correct, how to overcome the program to get the connection succeeded message box.
Well, you're filling the ds data set - but then you're checking the dt data table for presence of rows... that's never going to work, of course!
If you only need a single DataTable - just use and fill that data table alone - no need for the overhead of a DataSet. Also, put your SqlConnection and SqlCommand into using blocks like this:
using (SqlConnection conn = new SqlConnection("Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****"))
using (SqlCommand cmd = new SqlCommand("Chatroomapp", conn))
{
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
// fill the data table - no need to explicitly call `conn.Open()` -
// the SqlDataAdapter automatically does this (and closes the connection, too)
DataTable dt = new DataTable();
adapt.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
And just because you get back no rows in dt.Rows doesn't necessarily mean that your connection failed..... it could just be that there are no rows that match your search critieria! The connection worked just fine - but the SQL command just didn't return any rows.
Connection failed means that something went wrong between your program and the database. No records returned does not mean that the connection failed. It just means that your table is empty - it contains no records.
Using ADO.NET and a stored procedures would have been a little different from what you have done it. If you need to check if the connection failed, maybe it is better to check the type of exception that is returned in the catch part.
Below is how I would have done it. I would have created a separate method that would have handled my call, and then in your button1_Click I would have just called this method:
public async Task<ChatRoom> GetAsync(string chatRoomId, string chatRoomName)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
await sqlConnection.OpenAsync();
using (SqlCommand sqlCommand = new SqlCommand("ChatRooms_Get", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomID", chatRoomId));
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomName", chatRoomName));
using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
{
ChatRoom chatRoom = null;
if (await sqlDataReader.ReadAsync())
{
chatRoom = new ChatRoom();
chatRoom.Id = sqlDataReader.GetFieldValue<string>(0);
chatRoom.Name = sqlDataReader.GetFieldValue<string>(1);
chatRooms.Add(chatRoom);
}
return chatRoom;
}
}
}
}
catch (Exception exception)
{
// Try checking if the connection failed here
throw exception;
}
}
My chat room domain model could have looked like this:
public class ChatRoom
{
public string Id { get; set; }
public string Name { get; set; }
}
And the stored procedure would have looked like this:
CREATE PROCEDURE [dbo].[ChatRooms_Get]
(
#ChatRoomID VARCHAR(100),
#ChatRoomName VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
ChatRoomID,
ChatRoomName
FROM
tblChatRoom
WHERE
ChatRoomID = #ChatRoomID
AND ChatRoomName = #ChatRoomName;
END
GO
And then in the calling method you would get the chatroom and do with it whatever you need to do with it. For this example I just checked if it exists or not:
try
{
ChatRoom chatRoom = await chatRoomRepository.GetAsync(chatRoomId, chatRoomName);
if (chatRoom != null)
{
MessageBox.Show("Record found");
}
else
{
MessageBox.Show("No record found");
}
}
catch (Exception exception)
{
throw exception;
}
I hope this can help.

Categories