SQL Server stored procedure waiting parameter - sql-server

I have a SQL Server stored procedure:
exec GetBob #id=3
But when I call this stored procedure in a function, I get the error:
The procedure or function expects the #id parameter
But #id is the correct parameter (get value).
public List<Bob> GetBob(int id)
{
try
{
connection();
con.Open();
DynamicParameters param = new DynamicParameters();
param.Add("#id", id);
IList<Bob> EmpList = SqlMapper.Query<Bob>(con, "GetBob", param).ToList();
con.Close();
return EmpList.ToList();
}
catch (Exception)
{
throw;
}
}

Try this. You should be good. You need to provide command Type that it is Stored Procedure.
public List<Bob> GetBob(int id)
{
try
{
connection();
con.Open();
DynamicParameters param = new DynamicParameters();
param.Add("#id", id);
IList<Bob> EmpList = SqlMapper.Query<Bob>(
con, "GetBob",param,commandType: CommandType.StoredProcedure).ToList();
con.Close();
return EmpList.ToList();
}
catch (Exception)
{
throw;
}
}

Related

Having trouble with SQL Delete on SQL Server using C#

I am running this code but it throws an exception and I am not sure why. Any help would be appreciated. I checked the ID and it was the right ID for the record.
protected void DeleteSQLDB(int id)
{
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblStudent WHERE ID=" + id;
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
m_dbConnection.Open();
cmd.ExecuteNonQuery();
m_dbConnection.Close();
}
}
}
catch (Exception ex)
{
Response.Redirect("somwhere");
}
finally
{
}
}
I solved the problem. The reason was that the record was referenced in other tables so I had to remove the references before I could remove the record. Thanks user7396598 for advice about running query manually. This is the code which removes the conversations first and then the student record:
//This deletes the archived student, First any conversations need to be deleted before the record can be removed.
protected void DeleteSQLDB(object id,String studentID)
{
// Response.Redirect(studentID);
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblConversations WHERE StudentID=#studentID";
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#studentID", studentID);
m_dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
DeleteSQLDB2(id);
}
}
protected void DeleteSQLDB2(object id)
{
// Response.Redirect(studentID);
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblStudent WHERE ID=#ID";
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#ID", id);
m_dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
Response.Redirect("studentgrid.aspx");
}
}

How to connect to SQL Server from .Net Core without using Entity Framework?

How can we connect to SQL Server from .Net Core without using Entity Framework?
you can simply use the traditional way which use SqlConnection
here is an example
public class BaseDataAccess
{
protected string ConnectionString { get; set; }
public BaseDataAccess()
{
}
{
public BaseDataAccess(string connectionString)
private SqlConnection GetConnection()
this.ConnectionString = connectionString;
}
{
if (connection.State != ConnectionState.Open)
SqlConnection connection = new SqlConnection(this.ConnectionString);
connection.Open();
return connection;
SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);
}
protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)
{
protected SqlParameter GetParameter(string parameter, object value)
command.CommandType = commandType;
return command;
}
{
parameterObject.Direction = ParameterDirection.Input;
SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);
return parameterObject;
}
SqlParameter parameterObject = new SqlParameter(parameter, type); ;
protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
{
if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar || type == SqlDbType.NText || type == SqlDbType.Text)
{
}
parameterObject.Size = -1;
}
parameterObject.Direction = parameterDirection;
if (value != null)
{
parameterObject.Value = value;
}
else
{
parameterObject.Value = DBNull.Value;
}
return parameterObject;
DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
{
int returnValue = -1;
try
{
using (SqlConnection connection = this.GetConnection())
{
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
using (DbConnection connection = this.GetConnection())
returnValue = cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//LogException("Failed to ExecuteNonQuery for " + procedureName, ex, parameters);
throw;
}
return returnValue;
}
protected object ExecuteScalar(string procedureName, List<SqlParameter> parameters)
{
object returnValue = null;
try
{
{
}
DbCommand cmd = this.GetCommand(connection, procedureName, CommandType.StoredProcedure);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
returnValue = cmd.ExecuteScalar();
}
}
catch (Exception ex)
{
//LogException("Failed to ExecuteScalar for " + procedureName, ex, parameters);
throw;
return returnValue;
}
ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);
protected DbDataReader GetDataReader(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
{
DbDataReader ds;
try
{
DbConnection connection = this.GetConnection();
{
DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
}
}
catch (Exception ex)
{
}
//LogException("Failed to GetDataReader for " + procedureName, ex, parameters);
throw;
}
return ds;
}
More can be find here
Update
you have to add nuget package
Install-Package System.Data.SqlClient
that is still confusing for me... .Net Core & .Net standard vs regular .Net: How do we know which packages we can use with .Net core?
Dependencies means that what you should have installed on your machine in order to use the package or nuget will install it for you
to understand more how dependencies work in .net take a look here
Note
that if the nuget package target .net standard library mostly work on both .net core and .net standard framework
If you surprised with BaseDataAccess class format in another answer and referenced article same as me, here is well formatted example... hopefully it will save you some time
public class BaseDataAccess
{
protected string ConnectionString { get; set; }
public BaseDataAccess()
{
}
public BaseDataAccess(string connectionString)
{
this.ConnectionString = connectionString;
}
private SqlConnection GetConnection()
{
SqlConnection connection = new SqlConnection(this.ConnectionString);
if (connection.State != ConnectionState.Open)
connection.Open();
return connection;
}
protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)
{
SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);
command.CommandType = commandType;
return command;
}
protected SqlParameter GetParameter(string parameter, object value)
{
SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);
parameterObject.Direction = ParameterDirection.Input;
return parameterObject;
}
protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
{
SqlParameter parameterObject = new SqlParameter(parameter, type); ;
if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar || type == SqlDbType.NText || type == SqlDbType.Text)
{
parameterObject.Size = -1;
}
parameterObject.Direction = parameterDirection;
if (value != null)
{
parameterObject.Value = value;
}
else
{
parameterObject.Value = DBNull.Value;
}
return parameterObject;
}
protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
{
int returnValue = -1;
try
{
using (SqlConnection connection = this.GetConnection())
{
DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
returnValue = cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//LogException("Failed to ExecuteNonQuery for " + procedureName, ex, parameters);
throw;
}
return returnValue;
}
protected object ExecuteScalar(string procedureName, List<SqlParameter> parameters)
{
object returnValue = null;
try
{
using (DbConnection connection = this.GetConnection())
{
DbCommand cmd = this.GetCommand(connection, procedureName, CommandType.StoredProcedure);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
returnValue = cmd.ExecuteScalar();
}
}
catch (Exception ex)
{
//LogException("Failed to ExecuteScalar for " + procedureName, ex, parameters);
throw;
}
return returnValue;
}
protected DbDataReader GetDataReader(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
{
DbDataReader ds;
try
{
DbConnection connection = this.GetConnection();
{
DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
catch (Exception ex)
{
//LogException("Failed to GetDataReader for " + procedureName, ex, parameters);
throw;
}
return ds;
}
}
Here is a solution for an ASP.NET MVC Core 3.1 project tested in Visual Studio 2019 community edition.
Create a small database in SQL Express.
Then add a few lines to appsettings.json for the connection strings:
"ConnectionStrings": {
//PROD on some server
"ProdConnection": "Server=somePRODServerofYours;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxxx_user;Password=xxsomepwdxx;Integrated Security=false;MultipleActiveResultSets=true;encrypt=true",
//DEV on localhost
"DevConnection": "Server=someDEVServerofYours;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxxx_user;Password=xxsomepwdxx;Integrated Security=false;MultipleActiveResultSets=true;"
},
Then use code similar to the following in your controller ....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace SomeNameSpace.Controllers
{
//This Model class should be saved somewhere else in your project.
//It is placed here for simplicity.
public class XtraSimpleContent
{
public string UserName { get; set; }
public string References { get; set; }
public string CreatedTime { get; set; }
}
public class CodeNotesController : Controller
{
public IConfiguration Configuration { get; }
public string connStr = String.Empty;
public CodeNotesController(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
if (env.IsDevelopment())
{
connStr = Configuration.GetConnectionString("DevConnection");
}
else
{
connStr = Configuration.GetConnectionString("ProdConnection");
}
}
[HttpGet]
public async Task<IActionResult> CodeActionMethodToConnectToSQLnetCore()
{
//add using System.Data.SqlClient;
// using System.Data;
//Along with the using statements, you need the system assembly reference.
//To add assembly you can do the following.
// install nuget package. Right Click on Project > Manage Nuget Packages >
// Search & install 'System.Data.SqlClient' and make sure it is compatible with the type of project (Core/Standard);
List<XtraSimpleContent> aListOfItems = new List<XtraSimpleContent>();
string commandText = #"SELECT * FROM [dbo].[ItemSubmissions]
WHERE SUBMITTEREMAIL = #SUBMITTEREMAIL
ORDER BY CreationDatetime DESC";
using (var connection = new SqlConnection(connStr))
{
await connection.OpenAsync(); //vs connection.Open();
using (var tran = connection.BeginTransaction())
{
using (var command = new SqlCommand(commandText, connection, tran))
{
try
{
command.Parameters.Add("#SUBMITTEREMAIL", SqlDbType.NVarChar);
command.Parameters["#SUBMITTEREMAIL"].Value = "me#someDomain.org";
SqlDataReader rdr = await command.ExecuteReaderAsync(); // vs also alternatives, command.ExecuteReader(); or await command.ExecuteNonQueryAsync();
while (rdr.Read())
{
var itemContent = new XtraSimpleContent();
itemContent.UserName = rdr["RCD_SUBMITTERNAME"].ToString();
itemContent.References = rdr["RCD_REFERENCES"].ToString();
itemContent.CreatedTime = rdr["CreationDatetime"].ToString();
aListOfItems.Add(itemContent);
}
await rdr.CloseAsync();
}
catch (Exception Ex)
{
await connection.CloseAsync()
string msg = Ex.Message.ToString();
tran.Rollback();
throw;
}
}
}
}
string totalinfo = string.Empty;
foreach (var itm in aListOfItems)
{
totalinfo = totalinfo + itm.UserName + itm.References + itm.CreatedTime;
}
return Content(totalinfo);
}
}
}
Test it with something like:
https://localhost:44302/CodeNotes/CodeActionMethodToConnectToSQLnetCore
With UkrGuru.SqlJson package
appsettings.json:
"ConnectionStrings": {
"SqlJsonConnection": "Server=localhost;Database=SqlJsonDemo;Integrated Security=SSPI"
}
Startup.cs
services.AddSqlJson(Configuration.GetConnectionString("SqlJsonConnection"));
DbController.cs
[ApiController]
[Route("api/[controller]")]
public class DbController : ControllerBase
{
private readonly string _prefix = "api.";
private readonly DbService _db;
public DbController(DbService db) => _db = db;
[HttpGet("{proc}")]
public async Task<string> Get(string proc, string data = null)
{
try
{
return await _db.FromProcAsync($"{_prefix}{proc}", data);
}
catch (Exception ex)
{
return await Task.FromResult($"Error: {ex.Message}");
}
}
[HttpPost("{proc}")]
public async Task<dynamic> Post(string proc, [FromBody] dynamic data = null)
{
try
{
return await _db.FromProcAsync<dynamic>($"{_prefix}{proc}",
(object)data == null ? null : data);
}
catch (Exception ex)
{
return await Task.FromResult($"Error: {ex.Message}");
}
}
}

How to Assign variable?

I don't know how to assign value return from stored procedure into web api? how to pass variables througn angulrjs
I called serivice
var promisePost = crudService.candidatePost(Candidates);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
}, function (err) {
alert("NOt Inserted")
});
my app.js is
MyApp.service('crudService', function ($http, RESOURCES) {
this.candidatePost = function (Candidate) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCandidate",
data: Candidate
});
return request;
}
});
my controller is
[HttpPost]
[Route("api/saveCandidate")]
public HttpResponseMessage AddDetail(Candidate ct)
{
SqlConnection con = new SqlConnection(Constant.ConnectionString);
SqlCommand cmd = new SqlCommand();
int rowInserted = 0;
try
{
cmd = new SqlCommand("sp_Insert_tblCandidate", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", ct.Name);
cmd.Parameters.AddWithValue("#Gender", ct.Gender);
cmd.Parameters.AddWithValue("#Dob", ct.Dob);
cmd.Parameters.AddWithValue("#Mob", ct.Mob);
cmd.Parameters.AddWithValue("#EntryDate", ct.EntryDate);
cmd.Parameters.AddWithValue("#Note", ct.Note);
cmd.Parameters.AddWithValue("#Emial", ct.Emial);
cmd.Parameters.AddWithValue("#Address", ct.Address);
rowInserted = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception obj)
{
if (rowInserted != 1)
{
var message = obj.Message;// string.Format("Insertion Of Data is not Succefully Executed");
HttpError err = new HttpError();
return Request.CreateResponse(HttpStatusCode.NotFound, err);
}
}
finally
{
if (con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
}
var alertmessage = string.Format("Insertion Of Data is Succefully Executed");
return Request.CreateResponse(HttpStatusCode.OK, alertmessage);
}
My stored Procedure is
IF EXISTS ( SELECT *
FROM sysobjects
WHERE id = object_id(N'[dbo].[sp_Insert_tblCandidate]')
and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
DROP PROCEDURE [dbo].[sp_Insert_tblCandidate]
END
GO
Create procedure [dbo].[sp_Insert_tblCandidate]
(#Name varchar(50) ,
#Gender char(1),
#dob varchar(25),
#Mob varchar(15),
#EntryDate varchar(50),
#Note varchar(100),
#Emial varchar(50),
#Address varchar(50)
)As
Begin
INSERT INTO [dbo].[tblCandidate] VALUES (#Name,#Gender,#dob,#Mob,#EntryDate,#Note,#Emial,#Address);
SELECT SCOPE_IDENTITY() as CandidateId;
end
GO
My stored procedure purpose is insert data & return last inserted id. In this table id set to auto increment.Anyone can help me?
You are returning the new Id so you shouldn't be using
cmd.ExecuteNonQuery()
But something that can handle the return value. Try changing it to
rowInserted = (int) cmd.ExecuteScalar();
Also right now you are checking in the catch the rowInserted which doesn't makes much sense.
You cannot get a result from ExecuteNonQuery() as it only returns the number of rows affected for the query you just executed.
Since you are returning the SCOPE_IDENTITY(), you can either use ExecuteReader() or ExecuteScalar().
rowInserted = (int)cmd.ExecuteScalar();
or
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
rowInserted = Convert.ToInt32(rdr[0]);
}
}
But using SqlDataReader is kinda unnecessary in this scenario.
Plus, just an observation; be careful when choosing between SCOPE_IDENTITY(), ##IDENTITY and IDENT_CURRENT.

how do I send datagridview data to sql server?

I tried to send datagridview data to sql server. I have logic layer and a data layer
// calling logic layer
RecLogic.ProcessRecoveryData(dataGridView1.DataSource)
then i access that datasource from datalayer
//this is my logic class
public void ProcessRecoveryData(object dataSource)
{
try
{
new RecoveryData().ProcessRecoveryData(dataSource);
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
hen i access that datasource from logic layer
//this is my data class
public void ProcessRecoveryData(object dataSource)
{
try
{
sqlCon.Open();
sqlCmd.Connection = sqlCon;
SqlDataAdapter sqlAdp = new SqlDataAdapter();
for (int i = 0; i < dataGridView1.dataSource.Rows.Count; i++)
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "my_sp"; sqlCmd.Parameters.AddWithValue("#p1",dataGridView1.dataSource.Rows[i].Cells["text"].Value); sqlCmd.Parameters.AddWithValue("#p2",dataGridView1.dataSource.Rows[i].Cells["text"].Value);
sqlAdp.SelectCommand = sqlCmd;
}
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCmd.Dispose();
}
}
how can i send datasource in data layer to sql?
You need to define a Table type and have a parameter of that type in your stored procedure......
eg
In SQL....
CREATE TYPE myTableType AS table (
categoryBridgeId uniqueIdentifier,
denomination int,
qty int
);
CREATE PROCEDURE [dbo].[My_Sproc] (#items myTableType READONLY,
etc
Then in C# you can pass a DataTable to the storred procedure...
..
var tblParam = new SqlParameter("#items", SqlDbType.Structured);
tblParam.Value = GetItemsAsDataTable(req);
tblParam.TypeName = "dbo.myTableType ";
cmd.Parameters.Add(tblParam);
...
private static DataTable GetItemsAsDataTable(ECodeAddItemsToBasketRequest req)
{
var result = new DataTable();
result.Columns.Add("categoryBridgeId", typeof(Guid));
result.Columns.Add("denomination", typeof(int));
result.Columns.Add("qty", typeof(int));
foreach (var item in req.ps)
{
Guid category = item.cid;
int denomination = item.d;
int qty = item.q;
result.Rows.Add(category, denomination, qty);
}
return result;
}
Hope this helps - Good luck!

Executed Stored Procedure using Dapper

I am trying to execute a stored procedure using Dapper but I get two types of errors:
Error parsing column 9 (fTaxInvoiceNumber=INV0000000028PPN - String)
Object reference not set to an instance of an object
Here is the code to execute the stored procedure:
SqlConnection db = new SqlConnection(ConnectionFactory.ConnectionString("RebateSystem"));
db.Open();
try
{
var result = db.Query<PracticeRebateOrders>("GetPracticeRebateOrderByInvoiceNumber", new
{
TaxInvoiceNumber = InvoiceNumber
}, commandType: CommandType.StoredProcedure).FirstOrDefault();
db.Close();
db.Dispose();
return result;
}
catch (Exception ex)
{
throw;
}
This is my stored procedure:
ALTER PROCEDURE [dbo].[GetPracticeRebateOrderByInvoiceNumber]
#TaxInvoiceNumber NVARCHAR(20)
AS
BEGIN
SELECT TOP(1)
[fPracticeRebateOrdersID]
,[fPracticeID]
,[fPracticeUserID]
,[fCreatedDate]
,[fInvoiceInCredits]
,[fPurchaseDate]
,[fPracticeRebateOrderStatusID]
,[fRebatePaymentRunID]
,[fRebateBatchID]
,[fTaxInvoiceNumber]
FROM
[PracticeRebateSystem].[dbo].[PracticeRebateOrders]
WHERE
fTaxInvoiceNumber = #TaxInvoiceNumber
END
Not really an answer, but based on the code available in the question and in the comments I have this... which works fine and successfully...
public void SO24605346_ProcsAndStrings()
{
connection.Execute(#"create proc #GetPracticeRebateOrderByInvoiceNumber #TaxInvoiceNumber nvarchar(20) as
select #TaxInvoiceNumber as [fTaxInvoiceNumber]");
string InvoiceNumber = "INV0000000028PPN";
var result = connection.Query<PracticeRebateOrders>("#GetPracticeRebateOrderByInvoiceNumber", new
{
TaxInvoiceNumber = InvoiceNumber
}, commandType: CommandType.StoredProcedure).FirstOrDefault();
result.TaxInvoiceNumber.IsEqualTo("INV0000000028PPN");
}
class PracticeRebateOrders
{
public string fTaxInvoiceNumber;
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TaxInvoiceNumber { get { return fTaxInvoiceNumber; } set { fTaxInvoiceNumber = value; } }
}
I'm happy to help, but I cannot reproduce an issue. Looks fine here.

Resources