I have an issue executing a stored procedure using Dapper with Mysql (MariaDB).
Here is the stored procedure:
CREATE DEFINER = `user` #`%`
PROCEDURE database.`proc_EnterRow`(
IN `_entity_number` INT(11),
IN `_price` DECIMAL(19, 13),
IN `_valuation_date` DATETIME)
LANGUAGE SQL
NOT DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
BEGIN
INSERT INTO tablename (entity_number,
entity_name,
valuation_date,
units,
price,
investor_code,
currency,
provisional,
isin,
type,
batchno,
maturity_date,
fx_rate,
transaction_id,
bond_reserves,
bond_reserves_percentage,
bond_reserves_conv,
sold,
verified)
SELECT entity_number,
entity_name,
_valuation_date,
units,
_price,
investor_code,
currency,
provisional,
isin,
type,
batchno,
maturity_date,
fx_rate,
transaction_id,
bond_reserves,
bond_reserves_percentage,
bond_reserves_conv,
sold,
verified
FROM tablename2 v
WHERE v.entity_number = _entity_number`;
END;
The stored procedure works fine when I execute from an sql editor using
call proc_EnterRow(111,123.5456,'2021-07-09');
But when I call it from my .Net Core with Dapper ORM I keep getting the error message
Incorrect number of arguments for PROCEDURE database.proc_EnterRow; expected 3, got 0
My code .Net code
DynamicParameters_parameters = new DynamicParameters();
_parameters.Add("#_entity_number", 111, DbType.Int32, SetDirection(parameterDirection), 11);
_parameters.Add("#_price", 123.5501, DbType.Decimal, SetDirection(parameterDirection));
_parameters.Add("#_valuation_date", "2021-01-01", DbType.Date, SetDirection(parameterDirection);
_dapper.Execute("dbname.proc_EnterRow", _parameters, commandType: CommandType.StoredProcedure);
Thank you in advance for your help.
var resulst = _dapper.Query<YourEntity>("dbname.proc_EnterRow",
new { _entity_number = 111, _price = 123.5501, _valuation_date = 2021-07-09},
commandType: CommandType.StoredProcedure);
Seems your are trying to execute a stored procedure on your Maria Db from ASP.NET Core.
You are getting the error because the stored procedure parameters haven't been passed exactly.
You could try this way:
string name = "Kiron Test";
int employeeId = 520520;
int totalPrint = 10;
var enterNewRowInDb = new List<PrinterJob>();
enterNewRowInDb = _context.PrinterJobs
.FromSql("proc_EnterRow {0}, {1},{2}",name,employeeId,totalPrint)
.ToList();
Output:
Another way:
using (var connection = new SqlConnection("Server=ServerName;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "proc_EnterRow";
command.Parameters.AddWithValue("#Name", name);
command.Parameters.AddWithValue("#EmployeeId", employeeId);
command.Parameters.AddWithValue("#TotalPrint", totalPrint);
command.ExecuteNonQuery();
connection.Close();
}
Note: it won't return your select query data. To get that you have to execute a data reader operations.
Hope it would help you. Let me know if you any further concern.
Related
I have a procedure where I am using OPENJSON to display the Json string as key value pairs. When I execute the procedure, it is returning the expected value bu in controller, the dataset is empty. It only shows the table headers - key, value, type. No data at all. When I use a different very similar procedure, it it seems to work fine. Not sure what is happening. Please help!
Thanks in advance!
This is my procedure:
CREATE PROCEDURE [dbo].[PROC_NH_Journal_Tab1Data]
#EnterpriseId nvarchar,
#exactgroup nvarchar
AS
declare #json nvarchar(max)
set #json=(select Tab2Json from tbl_NH_T_JournalDataPost where
EnterpriseId=#EnterpriseId and GroupName = #exactgroup)
SELECT * FROM
OPENJSON ( #json )
Return 0
And here is my action:
public JsonResult GetAnswersFortab1(string exact)
{
string JSONresult = string.Empty;
string EnterpriseId = "User";
try
{
SqlConnection sqlcon = new SqlConnection(con);
SqlCommand cmd = new SqlCommand("[PROC_NH_Journal_Tab1Data]", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EnterpriseId", EnterpriseId);
cmd.Parameters.AddWithValue("#exactgroup", exact);
sqlcon.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet data;
data = new DataSet();
adapter.Fill(data, "Table2");
DataTable dt1 = data.Tables[0];
ViewBag.getJson = dt1;
}
The procedure when executed, gives a table with key, value pairs. But when I debug,in action, the 'data' is an empty table in 'DataSetVisualizer'. Empty table only with headers(key,value,type).No data is present.
Here is my Print #json from the procedure
key value type
emoji2 2 1
check2 on 1
check5 on 1
check7 on 1
hiddentext weds 1
From the below source tutorials:
https://www.youtube.com/watch?v=Jt9vSY802mM
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
How do I do the above code samples without Entity Framework, by just using SQL queries?
For example in the above source code, instead of
var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault();
if (v != null)
{
dc.Events.Remove(v);
dc.SaveChanges();
status = true;
}
I want to do
DELETE FROM Even WHERE EventID = {0}
FirstOrDefault() in LINQ is equivalent to LIMIT 1 in MySQL, hence the LINQ function can be converted to SQL commands using IF or CASE WHEN like this (assumed commands are running inside a stored procedure):
DELIMITER //
-- 'Events' is a DbSet name by common convention,
-- therefore table name should be 'Event'
CREATE PROCEDURE procedure_name (IN eventID INT)
BEGIN
DECLARE v INT;
SET v = SELECT EventID FROM Event WHERE EventID = eventID LIMIT 1;
CASE WHEN v IS NOT NULL
THEN DELETE FROM Event WHERE EventID = v
ELSE -- do something else
END
-- alternative:
-- IF(v IS NOT NULL, DELETE FROM Event WHERE eventID = v, 0)
-- other stuff here
END//
DELIMITER ;
Note: If EventID is a primary key column, you can remove LIMIT 1 because query result only return single value.
Then, use CALL procedure_name(eventID) or include procedure_name in MySqlCommand to execute it.
Couple of ways:
using raw query in Entity Framework:
Open connection string via SqlConnection and execute:
Pseudo code for method 1:
string sqlDeleteStatement = "DELETE FROM Even WHERE EventID = #id";
List<SqlParameter> parameterList = new List<SqlParameter>();
parameterList.Add(new SqlParameter("#id", 1)); delete id = 1
_context.Database.SqlQuery(sqlDeleteStatement, parameterList);
Pseudo code for method 2:
using(SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Server=[server_name];Database=[database_name];Trusted_Connection=true";
string sqlDeleteStatement = "DELETE FROM Even WHERE EventID = #id";
SqlCommand command = new SqlCommand(sqlDeleteStatement , conn);
command.Parameters.Add(new SqlParameter("#id", 1)); //delete id = 1
command.ExecuteNonQuery();
}
for (int n = 0; n < scoreDocs.Length; ++n)
{
doc = new Document();
ScoreDoc sd = scoreDocs[n];
float score = sd.Score;
int docId = sd.Doc;
doc = searcher.Doc(docId);
string userId = doc.GetField("userID").StringValue;
UserID id = new UserID();
id.user_ID = Convert.ToInt32(userId);
QueryUsers.Add(id);
}
I want to send this List of Id s to Mysql DB , so how can I receive there in my sql Stored procedure ? please writ Stored procedure thanks
Refer to this examples, it will help you :
JDBC CallableStatement – Stored Procedure IN parameter example
Calling Stored Procedures in JDBC Programs
I need to call from a asp page a stored procedure I have in SQL 2008 and pass to it two values and at the end return the count of two variables.
this is the stored procedure I have:
/****** STUDATATAB******/
CREATE PROCEDURE StdntReconcileDups #NewSTDNT int = NULL, #OldSTDNT int = NULL output
AS
--use ZLDP01RD;
--count = 9 rows
Select count (*) from STUDATA.dbo.STUDATATAB
where STDNT = #NewSTDNT;
-- count = 576 rows
select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #OldSTDNT;
-- select duplicate keys with new student# count = 3 rows
select a.STDNT,a.crs,a.CRS_VRSN,a.QSTN,a.SCR
from STUDATA.dbo.STUDATATABa, STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR
-- select duplicate keys with new student# count = 3 rows
select count (*)
from STUDATA.dbo.STUDATATABa
where exists (select 1 from STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR );
-- delete duplicate keys with new student# 3 rows deleted
WITH STUDENT_CTE
AS
(select a.*
from STUDATA.dbo.STUDATATABa
where exists (select 1 from STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR ))
delete from STUDENT_CTE;
--Convert student #10826 history records to student #123196, should update 579 rows
UPDATE STUDATA.dbo.STUDATATAB
SET STDNT = #NewSTDNT, LSTUPDT_USER_ID_CD = 'DFERN', LSTUPDT_TS = getDate()
where STDNT = #OldSTDNT;
-- count= 582
select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #NewSTDNT;
-- count= 0
Select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #OldSTDNT;
go
I want to insert the code in the if argument so it calls StdntReconcileDups and pass to it the values of KeepSTDNT and RemoveSTDNT
Dim DBConn ' Connection object
If Request.Form("Action") = "Go!" then
Endif
If I got your meaning...then do like below:
SqlConnection con = new SqlConnection("Data Source= ; initial catalog= Northwind ; User Id= ; Password= '");
con.open();
After creating SqlConnection you will create Storedprocedure like below:
CREATE PROCEDURE RegionUpdate (#RegionID INTEGER,#RegionDescription NCHAR(50)) AS
SET NOCOUNT OFF
UPDATE Region
SET RegionDescription = #RegionDescription
Create a SqlCommand object with the parameters as the name of the stored procedure that is to be executed and the connection object con to which the command is to be sent for execution.
SqlCommand command = new SqlCommand("RegionUpdate",con);
Change the command objects CommandType property to stored procedure.
command.CommandType = CommandType.StoredProcedure;
Add the parameters to the command object using the Parameters collection and the SqlParameter class.
command.Parameters.Add(new SqlParameter("#RegionID",SqlDbType.Int,0,"RegionID"));
command.Parameters.Add(new SqlParameter("#RegionDescription",SqlDbType.NChar,50,"RegionDescription"));
Specify the values of the parameters using the Value property of the parameters
command.Parameters[0].Value=4;
command.Parameters[1].Value="SouthEast";
Excecute the stored procedure using the ExecuteNonQuery method which returns the number of rows effected by the stored procedure.
int i=command.ExecuteNonQuery();
The code above is the right way...You can replace #KeepSTDNT and #RemoveSTDNT exactly instead of #RegionID and #RegionDescription...I have used it myself...if you wanna more help...tell then
the concept is the exeute your request ... you will get back a recordset which you will iterate over until you get to eof... then you will call next recordset to get to the next result.
... are you looking for something like this?
connectstring = "..."
sql = "StdntReconcileDups '" & NewSTDNT & "','" & OldSTDNT & "'"
set rs = Server.CreateObject("ADODB.RecordSet")
rs.Open sql, connectstring, 3
my table:
id address tag
1 test class1
2 test1 class2
3 test3 class3
In UI i am displaying all tag names as checkboxes.
When user selects one or more tag names then need to get required address values. how to get?
if user selects class1,class2 in UI then need to get test,test1 as result.
Please tell me how to write query in sqlserver 2008 for that.
EDIT CODE :
taglist = "class1,class2";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("usp_GetTags", con);
cmd.Parameters.Add("#Tags", SqlDbType.VarChar).Value = taglist;
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
while passing the parameters as above not getting any results.if i pass single taglist=class1 getting results.but taglist="class1,class2" not getting any resuls.please tell me how to pass multiple parameters from UI.
You can write the query in sql server by using the IN keyword.
Select address from mytable where tag IN ('class1','class2')
EDIT:
Add the parameters with values to the stored procedure like this. The below code is written in C#.net
comand.Parameters.AddWithValue("#Parameter1", "class1");
comand.Parameters.AddWithValue("#Parameter2", "class2");
EDIT 2:
Its very simple to put in a single string all the values, accordingly your query also suits that. Write the query in your stored procedure like
Select address from mytable where tag IN (#SingleParameter)
and in your coding part write like follow
string SingleParameter = "";
SingleParameter = "class1,class2,class3";
comand.Parameters.AddWithValue("#SingleParameter",SingleParameter);
EDIT 3:
Finally i found the solution for your problem. Write your stored procedure as below
ALTER PROCEDURE dbo.TestSP
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
#SingleParameter varchar(30)
AS
/* SET NOCOUNT ON */
declare #tags varchar(500)
set #tags = #SingleParameter
create table #t (tag varchar(10))
set #tags = 'insert #t select ' + replace(#tags, ',', ' union select ')
exec(#tags)
Select address from sample1 where (tag in (select tag from #t))
drop table #t
RETURN
and also send the parameters SingleParameter as below
string SingleParameter = "";
SingleParameter = "'class1','class2','class3'";
comand.Parameters.AddWithValue("#SingleParameter",SingleParameter);