How to add integer value in sql select query? - mysql

I'm working on a project where my sql query is
SELECT Name
FROM techer_reg
LIMIT 3
How can I add an integer value instead of 3?
In the sense, this select query should be look like:
SELECT Name
FROM techer_reg
LIMIT (My integer value)

Try using a parameter:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
int myLimit = 4;
using (SqlCommand com = new SqlCommand("SELECT Name FROM techer_reg LIMIT #LM", con))
{
com.Parameters.AddWithValue("#LM", myLimit);
using (SqlDataReader reader = com.ExecuteReader())
{
while (reader.Read())
{
int id = (int)reader["iD"];
string desc = (string)reader["description"];
Console.WriteLine("ID: {0}\n {1}", iD, desc);
}
}
}
}

procedure:
DELIMITER $
create PROCEDURE getData(limit INT)
begin
SET #limit= limit;
PREPARE exec_statment FROM "SELECT Name FROM techer_reg LIMIT limit ?;";
EXECUTE exec_statment USING #limit;
DEALLOCATE PREPARE exec_statment;
end$
DELIMITER ;
and call it using
call getData(3)

Related

.NetCore MariaDb Dapper - How to Execute Stored procedure?

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.

MVC with no Entity Framework

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

execute stored procedure in classic asp and return values

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

How to check more column values at a time in sqlserver 2008?

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

I need the metadata from a mysql resultset, is this possible?

I'd like to obtain the metadata from the results of a mysql query so I can put it into a datatable in c#. I primarily need the column name and the data type. Here's a simple example.
show columns from (
select sum(subtotal) as subtotal
, sum(tax1+tax2+tax3+tax4) as tax
, sum(subtotal)+sum(tax1+tax2+tax3+tax4) as total
from tbltransmaster
where batchnum in (
SELECT BatchNum
FROM tblshiftmaster
WHERE ClosingTS <> -1
ORDER BY OpeningTS ASC
)
) as x
It generates this error though
Error Code : 1064 You have an error in
your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near '(
select sum(subtotal) as subtotal
, sum(tax1+tax2+tax3+tax4) as tax
, sum' at line 1
Could someone provide me with some advice, or perhaps a link to assist with this?
show columns only works for actual tables and views, not for queries.
Since you mention C#, you're probably using ADO.NET ? You can directly fill a DataTable which figure out the data types and column names.
DbConnection conn = null;
DbConnection conn = null;
DbCommand cmd = null;
DbDataAdapter da = null;
DataTable tbl = new DataTable();
conn = new MySqlConnection(connectionString);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = query;
da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(tbl);
If you want to get the colum names only, you could fetch the result using a DataReader instead:
DbDataReader dbReader = cmd.ExecuteReader();
for (int i = 0; i < dbReader.FieldCount; i++) {
Type colType = dbReader.GetFieldType(i);
String colName = dbReader.GetName(i);
}
DbDataReader also have the .GetSchemaTable() which returns a DataTable describing the metadata of the result.