I´m working with Visual Studio 2010, SQL Server 2008, I created an application that sends mails, now my query is a simple select, but I need make it with a stored procedure, how can I replace that select for a stored procedure?
Here is my code:
public List<string> SqlSelectMails()
{
List<string> dir_mails = new List<string>();
**string stSql = "select mail_usuario from dbo.mail_usuario_v2 where n_visita=0 and
aviso=1 order by banca";**
Bd mibd = new Bd();
SqlDataReader sdr = mibd.sqlExecute(stSql);
while (sdr.Read())
{
dir_mails.Add(sdr["mail_usuario"].ToString());
}
return dir_mails;
}
I will like something like:
**string stSql = "exec pa_rep_mail";**
First you need to create the stored procedure in your database (using Sql Management Studio)
CREATE PROCEDURE [dbo].[pa_rep_mail]
AS
select mail_usuario
from dbo.mail_usuario_v2
where n_visita=0 and aviso=1
order by banca
then you need to call it from your code
using(SqlConnection cn = new SqlConnection(constring))
{
cn.Open();
SqlCommand cmd = new SqlCommand("pa_rep_mail", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
dir_mails.Add(sdr["mail_usuario"].ToString());
}
}
of course it is up to you to integrate this code in your existing code. In particular how to replace the call to mibd.sqlExecute(stSql);
Related
I have a stored procedure with parameters, which i want to submit the parameters in a view which returns a index of the list. How do i go about this in my controller
CREATE PROCEDURE [dbo].[spFlugReport]
(
#AccNo INTEGER,
#DateFrom DATE,
#DateTo DATE
)
AS
BEGIN
SELECT *
FROM [dbo].[KIRData]
WHERE AccNo = #AccNo
AND StartDate >= #DateFrom
AND EndDate <= #DateTo
AND Prod = 'Air'
END
C# code:
public ActionResult Report()
{
using(DataModel db = new DataModel())
{
SqlParameter[] param = new SqlParameter[] {
new SqlParameter("#AccNo ,"),
new SqlParameter("#DateFrom ,"),
new SqlParameter("#DateTo ,")
};
}
}
welcome to stack overflow. Here is a useful link that could help you to achieve what you need to do.
https://csharp-station.com/Tutorial/AdoDotNet/Lesson07
and here is one with a similar question to your problem How to execute a stored procedure within C# program
However, here is an quick example of what you need to pass a parameter to a stored procedure.
// create and open a connection object
SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("CustOrderHist", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#CustomerID", custId));
// execute the command
SqlDataReader rdr = cmd.ExecuteReader();
Hope this helps you.
I believe you're looking for something like this. If not, could you provide more detail.
DataTable database = new DataTable();
string dbString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(dbString))
using (SqlCommand cmd = new SqlCommand("dbo.spFlugReport", con))
{
using(DataModel db = new DataModel())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AccNo", AccNo);
cmd.Parameters.AddWithValue("#DateFrom", DateFrom);
cmd.Parameters.AddWithValue("#DateTo", DateTo);
con.Open();
cmd.ExecuteNonQuery();
}
}
This link is how you created a ConnectionString for YourConnection: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string
I'm working on an ASP.NET Web Application with Visual Studio 2010. My target framework is ".NET Framework 4" and I'm sending queries to a SQL Server 2008 database which version is "Microsoft SQL Server 2008 R2 (SP2)".
I'm connecting using the following connection string "Data Source=XXXX;Initial Catalog=XXXX;Integrated Security=False;User Id=XXXX;Password= XXXX;MultipleActiveResultSets=True" and sending queries with the code below:
public static List<DataTable> getData(String query)
{
var results = new List<DataTable>();
try
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.CommandTimeout = 0;
using (SqlDataReader reader = command.executeReader())
{
do
{
while (reader.Read()) ;
var dataTable = new DataTable();
dataTable.Load(reader);
results.Add(dataTable);
} while (reader.NextResult());
}
connection.Close();
}
}
}
}
The query I'm sending is an Stored Procedure which returns two tables, at first it had a loop which calls another Stored Procedure depending on some internal condition, creation and insertion on a tempdb..#table and two SELECT statements.
But now it only contains:
SELECT 1,2,3,4,5
SELECT 6,7,8,9,0
I don't know why but the reader.NextResult() is always false so I never get the second table result.
Does anyone know what I'm doing wrong? What should I do to receive and read the two results from the query?
if this is using a stored proc you need something like this: notice the command type
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(myConnString))
{
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
cmd.CommandText = "myMultipleTablesSP";
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
conn.Close();
}
}
if for example you return 2 tables in your SP, like:
SELECT * FROM [TableA];
SELECT * FROM [TableB];
you would access this tables as:
DataTable tableA = ds.Tables[0];
DataTable tableB = ds.Tables[1];
OK, I have run some test and find out the problem is from dataTable.Load(reader); somehow and I don't know why and what is exactly happening behind that method.
but if you use
do {
while(reader.Read()) {
...
}
} while (reader.NextResult());
everything works as expected.
I am trying to execute a stored procedure in my Sql Server Database from an Asp.Net MVC project. I have set it up in a way that I can use it for testing purposes, which is why the variable "procedureTest" is a constant value (I know that "2044" is an existing record in my database). I will change this once I accomplish a successful run. Also, I know that my stored procedure works because I have executed it in Sql Server Management Studio successfully. The procedure has the task of adding ID from one table to another, but I have yet to see it appear in this table. I am not receiving an error in my catch block so I am kind of lost at the moment. I could definitely use your help.
try
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
int procedureTest = 2044;
var command = new SqlCommand("SELECT ID FROM Images WHERE ID = #id", connection);
var paramDate = new SqlParameter("#id", procedureTest);
command.Parameters.Add(paramDate);
var reader = command.ExecuteReader();
while (reader.Read())
{
var storedProcCommand = new SqlCommand("EXEC addToNotificationTable #ID", connection);
var paramId = new SqlParameter("#ID", reader.GetInt32(0));
storedProcCommand.Parameters.Add(paramId);
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
string exceptionCause = String.Format("An error occurred: '{0}'", e);
System.IO.File.WriteAllText(#"C:\Users\Nathan\Documents\Visual Studio 2013\Projects\MVCImageUpload\uploads\exception.txt", exceptionCause);
}
Stored Procedure:
CREATE PROCEDURE addToNotificationTable #ID int
AS
Insert NotificationTable (ID)
SELECT ID
FROM Images
Where ID = #ID
Change you code like this
while (reader.Read())
{
var storedProcCommand = new SqlCommand("EXEC addToNotificationTable #ID", connection);
var paramId = new SqlParameter("#ID", reader.GetInt32(0));
storedProcCommand.Parameters.Add(paramId);
storedProcCommand.ExecuteNonQuery();
}
First of all, you missed to specify the command type. Also using EXEC in SqlCommand is not a proper way.
Please try with the below code
while (reader.Read())
{
using(SqlCommand storedProcCommand = new SqlCommand("addToNotificationTable", connection)) //Specify only the SP name
{
storedProcCommand.CommandType = CommandType.StoredProcedure; //Indicates that Command to be executed is a stored procedure no a query
var paramId = new SqlParameter("#ID", reader.GetInt32(0));
storedProcCommand.Parameters.Add(paramId);
storedProcCommand.ExecuteNonQuery()
}
}
Since you are calling the sp inside a while loop, wrap the code in using() { } to automatically dispose the command object after each iteration
I'm working on "Time Table Scedualing using genetic algorithm project"
using C# and Sql server..
I divided the Project to 3 Layers (Data Access Layer , business Layer , And interfaces)
Data access layer contains:
(constructor initialize the connection object, Method to open the connection,Method to open the connection ,Method to read data from database, Method to insert , update ,delete data from database)
for example:
//Method to insert , update ,delete data from database
public void ExecuteCommand(string stored_procedure, SqlParameter[] param)
{
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = stored_procedure;
sqlcmd.Connection = sqlconnection;
if (param != null)
{
sqlcmd.Parameters.AddRange(param);
}
sqlcmd.ExecuteNonQuery();
}
Business Layer Contains class for each form
for example: ADD_PROF.class for "Add Professor Form"
....................
Now to get all data about professors from database,I create (GET_ALL_PROF) procedure and write this code into ADD_PROF Class
public DataTable GET_ALL_PROF() //copied and pasted down for verfing
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DataTable Dt = new DataTable();
Dt = DAL.SelectData("GET_ALL_PROF", null);
DAL.Close();
return Dt;
}
My Problem is ... I don't know how to get (Professors ID) from professor table in database and put it into a variable to pass it in genetic algorithm code IN C#?
the procedure in sql is
Create proc [dbo].[get_id_PROF]
as
select ID_PROF from [dbo].[PROFESSOR]
You could use a SqlDataReader for reading the data from your database and simply use it to store data from your database in your variables.
int professorId;
private static void ReadOrderData(string connectionString)
{
string queryString = "select ID_ST from [dbo].[PROFESSOR];";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// Call Read before accessing data.
if (reader.HasRows())
{
reader.Read();
professorId = reader.GetInt32(0);
// Call Close when done reading.
reader.Close();
}
}
}
}
Or you could try this to use a Stored Procedure:
int professorId;
using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String"))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Data is accessible through the DataReader object here.
reader.Read();
professorId = reader.GetInt32(0);
}
}
SqlDataReader
Helper Link
Helper Link
I have a SQL stored procedure that returns a column value (SQL data type: nchar(1)). The stored procedure runs and comes back with desired value when a parameter is passed. Based on this returned value, I want to divert the program flow. For this I need to read the value returned in an ASP.NET C# variable, but I am not sure how can I do this.
create procedure sproc_Type
#name as nchar(10)
AS
SELECT Type FROM Table WHERE Name = #name
I want to read Type value in .cs file and want to save it for later use.
SqlConnection conn = null;
SqlDataReader rdr = null;
conn = new
SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand(
"Stored_PROCEDURE_NAME", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#PARAMETER_NAME", PARAMETER_VALUE));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
var result = rdr["COLUMN_NAME"].ToString();
}
string connectionString = "(your connection string here)";
string commandText = "usp_YourStoredProc";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
// your code to fetch here.
}
conn.Close();
}