Sql Server Stored Procedure not executing from MVC - c#

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

Related

SQL Out parameter received as null while passing from C#

I am trying to populate a value in an out parameter but it is returned as null from the stored procedure.
But it works fine when I try to run the query through SSMS.
Stored procedure:
CREATE PROCEDURE [dbo].[USP_ABCD]
(#signal_xml AS NVARCHAR(MAX) OUT) -- this parameter includes the result in case
AS
BEGIN
DECLARE #signal_data XML
SET #signal_data = cast(#signal_xml as XML)
INSERT INTO DBLog
VALUES ('USP_ABCD', 'test', #signal_xml, ERROR_MESSAGE(), GETUTCDATE())
SET #signal_xml = 'ABCD';
END
C# code calling this stored procedure:
private static void runSP()
{
try
{
var temp = File.ReadAllText(#"abcd\TEST1.txt");
var conStr = System.Configuration.ConfigurationManager.ConnectionStrings["test"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
// Setup the command to execute the stored procedure.
command.CommandText = "dbo.USP_ABCD";
command.CommandType = CommandType.StoredProcedure;
// Set up the output parameter to retrieve the summary.
SqlParameter paramSignalXml = new SqlParameter("#signal_xml", SqlDbType.NVarChar, -1);
paramSignalXml.Direction = ParameterDirection.Output;
paramSignalXml.Value = temp;
command.Parameters.Add(paramSignalXml);
// Execute the stored procedure.
command.ExecuteNonQuery();
Console.WriteLine((String)(paramSignalXml.Value));
var retValue = (String)(paramSignalXml.Value);
connection.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Is it not possible to pass value to output parameter or am I missing something? Can someone help me with this? Thanks in advance.

Calling stored procedure with parameter to return list

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

Web API to call the stored Procedure and return Result

I am creating a Web API that accepts two input parameter called ACC. Created a stored procedure to insert or update the Account table in the SQL server. Account table has just two fields AccountID nvarchar(50) (primaryKey) and Cnt int
CREATE PROCEDURE [dbo].[usp_InserUpadte]
#Account_TT AS Account_TT READONLY
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRANSACTION;
MERGE dbo.[Account] prj
USING #Account_TT tt
ON prj.AccountID = tt.AccountID
WHEN MATCHED THEN UPDATE SET prj.Cnt = prj.Cnt+1
WHEN NOT MATCHED THEN INSERT (AccountID,Cnt)
VALUES (tt.AccountID, 1);
COMMIT TRANSACTION;
Now I tried to connect to the SQL server not sure how to how would I call the stored procedure into the ASP.NET Web API application and pass the Account ID in it to create or updadte the table
namespace WebService.Controllers
{
public class CreationController : ApiController
{
[HttpGet]
public HttpResponseMessage Get(string ACC)
{
string strcon = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
I know we can call the query directly like
var strQuery = "SELECT * from ACCOUNT where ACC = :ACC"
But dont know how to call the above stored procedure and pass the Account Value. Any help is greatly appreciated.
Here is the complete working example.
Please have a look on it.
string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
DbConnection.Open();
SqlCommand command = new SqlCommand("[dbo].[usp_InserUpadte]", DbConnection);
command.CommandType = CommandType.StoredProcedure;
//create type table
DataTable table = new DataTable();
table.Columns.Add("AccountID", typeof(string));
table.Rows.Add(ACC);
SqlParameter parameter = command.Parameters.AddWithValue("#Account_TT", table);
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "Account_TT";
command.ExecuteNonQuery();
DbConnection.Close();
To call a stored procedure you need to use a SqlCommand something like this:
string strcon = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
using (var connection = new SqlConnection(strcon)) {
using (var command = new SqlCommand("usp_InserUpadte", connection)) {
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Account_TT ", SqlDbType.NVarChar).Value = ACC;
command.Open();
var reader = command.ExecuteReader();
// Handle return data here
}
}

Call stored procedure with custom type parameter from c#?

I have a procedure with a custom type as follow:
CREATE PROCEDURE MyProc
#Arg1 CustomArgType readonly
AS
BEGIN
.
.
.
END
And where the custom type is:
CREATE TYPE dbo.CustomArgType as TABLE
(
SomeInt int not null
)
How can I call the above stored procedure in c#?
What kind of adapter can be used? Can an ORM like EF work with such a stored procedure?
To test that, I extended your stored proc to make it return the first row of the parameter table:
CREATE PROCEDURE MyProc
#Arg1 CustomArgType readonly
AS
BEGIN
select top 1 SomeInt from #Arg1
END
Now I can use the following code in C# to execute the stored procedure:
using (var conn = new SqlConnection("Data Source=localhost;Initial Catalog=temp;User ID=sa"))
{
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("SomeInt", typeof(Int32));
dt.Rows.Add(new Object[] { 3 });
var command = conn.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "MyProc";
command.Parameters.Add(new SqlParameter("#Arg1", dt));
object returnValue = command.ExecuteScalar();
}
returnValue is 3 which I expected (I inserted into the 1st row in the parameter table).
Unfortunately I don't know much about EF so I can't say if you can do the same.
You can define your table parameter as "Structured", and set its value to your list/table variable in C#. Example code below:
try
{
using (var conn = new SqlConnection(myConnectionString))
using (var command = new SqlCommand("MyProc", conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add(new SqlParameter("#Arg1", SqlDbType.Structured));
command.Parameters["#Arg1"].Value = myArgVariable;
command.Parameters["#Arg1"].TypeName = "dbo.CustomArgType";
conn.Open();
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw;
}
Reference: https://blogs.msdn.microsoft.com/felixmar/2010/10/27/how-to-create-and-execute-a-stored-procedure-using-a-table-as-a-parameter/

Call stored procedure (sending mails) in C#

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

Categories

Resources