How to pass an array of parameters to MySql select ... in - mysql

I wish to select an array of records with id 2, 4, 6 from a mysql database file. I am trying to pass an array of integers to a Mysql store procedure. But I fail to create a working stored procedure.
Would you help me compose one?
This is the C# code
public static List<PhotoComment> GetPhotos(int[] _ids)
{
MySqlConnection _con = Generals.GetConnnection();
List<PhotoComment> _comments = new List<PhotoComment>();
try
{
MySqlCommand _cmd = new MySqlCommand("Photos_GetPhotosByIDs", _con);
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.AddWithValue("#_ids", _ids);
_con.Open();
MySqlDataReader _reader = _cmd.ExecuteReader();
while (_reader.Read())
{
PhotoComment _comment = new PhotoComment(_reader.GetInt32("cID"), _reader.GetInt32("cFID"), _reader.GetString("cUser"), _reader.GetString("cContent"), _reader.GetDateTime("cDate"), _reader.GetBoolean("cChecked"));
_comments.Add(_comment);
}
_con.Close();
}
catch (Exception _ex)
{
_con.Close();
ReportMgr.ReportException(_ex.Message);
}
return _comments;
}
this is the mysql
CREATE DEFINER=root#localhost PROCEDURE Photos_GetPhotosByIDs(in _ids int[])
BEGIN
select * from tbl_photos where ID in _ids;
END

There are no array types in MySQL. You can use table (temporary table) instead. Fill the bale with id values and join tables to get desired result.

I'm not sure if I'm getting your question right but what I think you're asking is how to send multiple values into an input parameter of a stored procedure.
If that's what you're asking, the following link may help. Not sure if such a feature exists in MySql but in SQL Server, it's called "Table-Valued Parameters" - TVP in short.
TVP allows you to pass multiple values into a single input parameter. Hope this helps: https://msdn.microsoft.com/en-us/library/bb675163(v=vs.110).aspx

Related

ExecuteSqlCommand return -1?

I am trying to call a stored procedure from code , in ef core 2 i found that i can use context.database.ExecuteSqlCommand() function to execute any stored procedure in my database.
While the stored procedure works fine in my sql server instance :
calling it from my code , returns -1 result !?:
using (var context = new AZPDBDEMOGZContext(optionsBuilder.Options))
{
var existUser = context.Database.ExecuteSqlCommand("GetIdUsager_ByNomPrenomEmail #p0,#p1,#p2", parameters:new[] { "rouarouarouarouaroua", "wiem", "test#gmail.com" });
}
what m i doping wrong ?
ExecuteSqlCommand will only return a 'rows affected' integer for a DML query aka insert/update/delete. Your stored proc looks like its returning a result set so it returns -1 as you've not provided a statement that changes the data source. You'll need to create a POCO and use FromSql to populate it.

Returning an object from a stored procedure

I am trying to create a stored procedure which reads data from a local db and creates an object and returns it. My problem is i have not worked with stored procedures so i don't have much knowledge about it.
I know how to use stored procedures to store data to a database but i don't know how to return data through stored procedures.
Below is the stored procedure which i have created to return an object.
CREATE PROCEDURE [dbo].[get_Advertisements]
AS
BEGIN
Select * From Advertisements;
END
I know the above stored procedure only selects the records but What i want to do is :
Select one record at a time from the advertisement table
Create an object of advertisement class and pass the values read from the advertisement table
Return the object
Continue the above procedure until the full table is read.
Advertisement object has the following properties :
- topic
- content
How do i achieve this? Please help , i tried to do it myself but i am confused with the returning part.
Thank you for your time
try this :
this is for SQL server and ASP.NET
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable ds = new DataTable();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
// this should be always in web.config file
sql = "Select * from Advertisements";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
//in ds You will get a Table
foreach(DataRow row in thisTable.Rows)
{
foreach(DataColumn column in thisTable.Columns)
{
Response.write((row[column]+"</br>");
// read all values of table
}
}
}
catch (Exception ex)
{
}

Stored Procedure for multiple value with single parameter in SQL Server

I have this form in C# with a listbox where I selected 4 items. Now I want to make single stored procedure using which I can find data from single table for all this selected item with single parameter.
As I am a beginner when it comes to SQL Server, I completely don't know this type of procedure
Thanks, but this is not my question's answer
I want a Single Stored Procedure for all Items which are selected in ListBox
Create Procedure procedureName
(
#ItemName varchar(50),
)
AS
BEGIN
(
Select * from item_master where item_name = #ItemName
)
END
by this Query i can find data for one ItemName, but i want for all selected Items in Listbox, even I don't know the C# code also,
so plz help me....
This is a very simple example that does what you want. You would not want to use hard-coded connection strings, especially in-line, and you would want error-handling, but I am going for as much clarity as possible. You would also probably want to make the column length greater than 50 characters, but I made it match your column definition.
Also, I would recommend a generic approach, passing keys (column names) and values, so as to be able to use it for any sort of criteria, but you asked that I keep it to exactly what you require, so I trimmed it down to the essential.
This example returns all the Employees with FirstName matching any in the list passed to the stored procedure (as a user-defined table type).
First, create a user-defined table type (to hold the values you want to pass to the stored procedure) in your SQL Server database as follows:
CREATE TYPE [dbo].[FilterValues] AS TABLE(
[Value] [varchar](50) NOT NULL,
PRIMARY KEY CLUSTERED
(
[Value] ASC
)
)
The stored procedure to return the Employees looks as follows (note that it has the user-defined table type as the type of the single parameter passed in):
CREATE PROCEDURE [dbo].[GetEmployees] (
#FirstNameFilterValues dbo.FilterValues READONLY
)
AS
BEGIN
SELECT * FROM Employees
INNER JOIN #FirstNameFilterValues fv ON fv.Value = Employees.FirstName;
END
That's the SQL Server side done. To call it from C#, you can create a DataTable with a single column matching the column name and populate it with the values you want. In this simple example, I populate it with two names, but it could be as many as you want.
var filterValuesDataTable = new DataTable();
filterValuesDataTable.Columns.Add(new DataColumn("Value", typeof(string)) { AllowDBNull = false });
filterValuesDataTable.Rows.Add("Frodo");
filterValuesDataTable.Rows.Add("Sam");
using (var connection = new SqlConnection("server=.;Initial Catalog=Test;Integrated Security=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "GetEmployees";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#FirstNameFilterValues", filterValuesDataTable);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader["FirstName"], reader["LastName"]);
}
reader.Close();
}
}
connection.Close();
}

How to fetch a row from one table and insert it into another table and get new PK value

I have two similar tables on different databases.
Database1/TableA
Database2/TableA
I want to fetch a row from one table and insert it into other table on other server. Like:
Database1/TableA
Id State Name
500 OH John [Fetch this row]
Database2/TableA
Id State Name
1 OH John [Insert and fetch PK '1']
I tried this using bulkcopy and it works fine.
But problem is I need to get PK from the new insert as I need to populate another child table.
Is there any better way to achieve this? Please on C# code, no database linking or SQL queries. Just C# solutions. Or if query can be used in C# code that is fine. Any working example code with Dataset or Datarow will be great help.
Thanks!
First you need to get the row(s) from Database.TableA. You could for example use a SqlDataAdapter with a DataTable or a SqlDataReader.
SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.
You can use SqlCommand.ExecuteScalar to execute the insert command and retrieve the new ID in one query.
const String sqlSelect = "SELECT COL1,COl2,Col3 FROM TableA WHERE COL1=#COL1;"
const String sqlInsert = "INSERT INTO TableA (COl2,Col3)VALUES (#Col2,#Col3);"
+ "SELECT CAST(scope_identity() AS int)";
using (var con1 = new SqlConnection(db1ConnectionString))
using (var con2 = new SqlConnection(db2ConnectionString))
{
con1.Open();
con2.Open();
using(var selectCommand = new SqlCommand(sqlSelect, con1))
{
selectCommand.Parameters.AddWithValue("#COL1", 4711);
using (var reader = selectCommand.ExecuteReader())
{
if (reader.Read())
{
int newID;
using (var insertCommand = new SqlCommand(sqlInsert, con2))
{
for (int i = 0; i < reader.FieldCount; i++)
{
insertCommand.Parameters.AddWithValue("#" + reader.GetName(i), reader[i]);
}
newID = (int)insertCommand.ExecuteScalar();
}
}
}
}
}

Calling a stored procedure from within a CLR stored procedure with a table valued parameter

The situation:
One Clr stored procedure that builds a data table and then it tries to call an SQL Stored procedure with a TVP parameter.
The code:
public class tvp_test : System.Data.DataTable
{
public tvp_test()
{
this.Column.Add("field1",typeof(System.Int32));
this.Column.Add("field2",typeof(System.Int32));
}
}
.............................................................
{
var tvp = new tvp_test();
.............................................................
using(SqlConnection con = new SqlConnection("context connection=true"))
{
con.Open();
var command = con.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandTest = "prc_test";
command.Parameters.Add("#a",System.Data.SqlDbType.Structured);
command.Parameters["#a"].Value = tvp;
command.ExecuteNonQuery();
con.Close();
}
}
......................................................................
create procedure prc_test
#a tvp_test readonly
begin
insert into #tmp (field1,field2) /* #tmp is created before the call of the CLR SP */
select field1,field2 from #a
end
The problem:
The behavior is erratic. One time it works, after x (where x is random) calls it will give me y (where y is random) "severe error occurred" with no other details, and after that the cycle will start again. From what I see the problem is on the CLR SP side as when errors start to occur, the SQL SP can be changed and be faulty as the error remains the same.
Maybe there is no love between CLR SP and TVPs, but I didn't find any reference to that.
As a side note, when it works it may work for a long time, but if I delete the SPs plan then it will start faulting. (can't find the logic in that "trigger" also)
Any thoughts ?
Thank you in advance.
Looks like this line has an error.
command.CommandTest = "prc_test";
Change it to
command.CommandText = "prc_test";