Select Query Parameter from C# in a stored procedure - c#

How does a SQL Server query select from parameter? I just want to make it simple set select column based on my C# code. Is it possible?
Here is my stored procedure:
ALTER PROCEDURE [dbo].[GetMembersDetailGenerateChanceTop10000]
#EventId nvarchar(255),
#PeriodId nvarchar(255),
#QueryParam nvarchar(1000)
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT TOP 10000 #QueryParam
FROM ign..Chance_Generated cg
INNER JOIN ign..Contact c ON cg.ContactID = c.ContactId
LEFT JOIN ign..CustomerAddress ca ON ca.parentid = cg.contactid
LEFT JOIN ign..new_cardlevelconfig cl ON cl.new_cardlevelconfigid = c.new_cardlevel
LEFT JOIN ign..new_country co ON co.new_countryid = c.new_country
LEFT JOIN ign..new_province po ON po.new_provinceId = c.new_Province
LEFT JOIN ign..StringMap sm ON sm.AttributeValue = c.new_IDType
LEFT JOIN ign..new_city cy ON cy.new_cityId = c.new_CityCounty
LEFT JOIN ign..new_transactionheader th ON cg.New_Name COLLATE DATABASE_DEFAULT = th.new_name COLLATE DATABASE_DEFAULT
WHERE cg.EventId = #EventId
AND (ca.AddressNumber = '1' OR ca.AddressNumber IS NULL)
AND (sm.AttributeName IS NULL OR sm.AttributeName = 'new_idtype')
AND cg.periodId = #PeriodId
QueryParam, EventId, PeriodId will be filled from C# code.
Here is my C# code:
private List<GenerateModel> getDataTopFromStoreProcedure(string EventId, string PeriodId)
{
// query select parameter
string QueryParam = #"cg.Chance_Number, th.new_name as [th name], dateadd(HOUR,7,th.createdon) as [th createdon],
c.new_Initial, c.FirstName, c.LastName";
string ConnString = GenerateChance.Properties.Settings.Default["DB_ConnectionString"].ToString();
using (SqlConnection conn = new SqlConnection(ConnString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = GetMembersDetailGenerateChanceTop10000;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0; //no limit
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("QueryParam", QueryParam));
cmd.Parameters.Add(new SqlParameter("EventId", EventId));
cmd.Parameters.Add(new SqlParameter("PeriodId", PeriodId));
cmd.Connection = conn;
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new GenerateModel
{
ChanceNumber = reader["Chance_Number"].ToString(), //System.IndexOutOfRangeException Error
Receipt = reader["th name"].ToString(),
Date = reader["th createdon"].ToString(),
Initial = reader["new_Initial"].ToString(),
FirstName = reader["FirstName"].ToString(),
LastName = reader["LastName"].ToString(),
});
}
reader.Close();
}
}
return list;
}
I am confused as to how to implement his method because I want to get return of all select results in object model but I always get error
System.IndexOutOfRangeException : Chance_Number.
Honestly why do I use query select parameter is because I want to get value from checkedListBox1 that already I defined before by using this code get all checkedListBox1 value to determine select query.
string QueryParam = "cg.Chance_Number";//auto get chance_number as select mandatory
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
QueryParam += ", " + ((clsItemList)checkedListBox1.CheckedItems[i]).Value;
}

You have to use constructor with proper length for parameters as given below, to avoid the issue.Read more on SQLParameter
public SqlParameter (string parameterName, System.Data.SqlDbType dbType, int size);
cmd.Parameters.Add(new SqlParameter("QueryParam", SqlDbType.NVarChar,1000)).Value = QueryParam;
You need to make few more changes:
The way you have defined the procedure is wrong. You have to define the procedure as dynamic sql for the #queryparam to get concatenated to the SELECT query as given below:
DECLARE #selectStmt NVARCHAR(MAX) = ''
DECLARE #sqldefinition NVARCHAR(4000) = '#EventId nvarchar(255), #PeriodId nvarchar(255)'
SET #selectStmt += 'select distinct top 10000 ' + #QueryParam +
'from ign..Chance_Generated cg
inner join ign..Contact c on cg.ContactID = c.ContactId
left join ign..CustomerAddress ca on ca.parentid = cg.contactid
left join ign..new_cardlevelconfig cl on cl.new_cardlevelconfigid = c.new_cardlevel
left join ign..new_country co on co.new_countryid = c.new_country
left join ign..new_province po on po.new_provinceId = c.new_Province
left join ign..StringMap sm on sm.AttributeValue = c.new_IDType
left join ign..new_city cy on cy.new_cityId = c.new_CityCounty
left join ign..new_transactionheader th on cg.New_Name COLLATE DATABASE_DEFAULT = th.new_name COLLATE DATABASE_DEFAULT
where cg.EventId= '''+ #EventId +''' and (ca.AddressNumber = ''1'' or ca.AddressNumber is null) and (sm.AttributeName is null or sm.AttributeName = ''new_idtype'')
and cg.periodId = ''' + #PeriodId + ''';'
EXEC #sp_executesql #selectStmt, #sqldefinition, #EventId , #PeriodId
``
- Always refer the tables with proper schema in the query
ign.SchemaName.new_country
ign.SchemaName.new_province

Related

A subquery in SQL Server returned more than 1 value

I made a Stored Procedure in SQL SERVER. When I call the stored procedure in the c# application, the following error occurs: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, , >= or when the subquery is used as an expression
I don't understand why this error occurs, because I am returning 1 single INT value.
ALTER PROCEDURE [dbo].[spToevoegenUitslag]
#intPersoonID INT,
#intPersoonIDSnelsteRonde INT,
#intPersoonIDPolePosition INT,
#intGrandPrixID INT,
#intPuntenID INT,
#intSeizoenID INT,
#intID INT = NULL
AS
BEGIN
--Toevoegen punten van uitslag GrandPrix
SELECT #intID = COUNT(ID) + 1 FROM tblPuntenCoureur
INSERT INTO tblPuntenCoureur (ID, PersoonID, GrandPrixID, PuntenID, SeizoenID)
VALUES (#intID, #intPersoonID, #intGrandPrixID, #intPuntenID, #intSeizoenID)
--Toevoegen deelnemers van de GrandPrix
SELECT #intID = COUNT(ID) + 1 FROM tblGrandPrixPersoon
INSERT INTO tblGrandPrixPersoon (ID, GrandPrixID, PersoonID)
VALUES (#intID, #intGrandPrixID, #intPersoonID)
IF (SELECT ID FROM tblSnelsteRonde WHERE GrandPrixID = #intGrandPrixID AND SeizoenID = #intSeizoenID) IS NULL
BEGIN
SELECT #intID = COUNT(ID) + 1 FROM tblSnelsteRonde
INSERT INTO tblSnelsteRonde (ID, PersoonID, intPunt, GrandPrixID, SeizoenID)
VALUES (#intID, #intPersoonIDSnelsteRonde, 1, #intGrandPrixID, #intSeizoenID)
END
IF (SELECT ID FROM tblPolePosition WHERE GrandPrixID = #intGrandPrixID AND SeizoenID = #intSeizoenID) IS NULL
BEGIN
SELECT #intID = COUNT(ID) + 1 FROM tblPolePosition
INSERT INTO tblPolePosition (ID, PersoonID, GrandPrixID, SeizoenID)
VALUES (#intID, #intPersoonIDPolePosition, #intGrandPrixID, #intSeizoenID)
END
RETURN 1 --Toevoegen uitslag gelukt
END
c# code
using (SqlCommand cmd = new SqlCommand("spToevoegenUitslag", verbinding))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#intPersoonID", SqlDbType.Int).Value = PersoonID[0];
cmd.Parameters.Add("#intPersoonIDSnelsteRonde", SqlDbType.Int).Value = PersoonIDSnelsteRonde;
cmd.Parameters.Add("#intPersoonIDPolePosition", SqlDbType.Int).Value = PersoonIDPolePosition;
cmd.Parameters.Add("#intGrandPrixID", SqlDbType.Int).Value = GrandPrixID;
cmd.Parameters.Add("#intPuntenID", SqlDbType.Int).Value = PuntenID[0];
cmd.Parameters.Add("#intSeizoenID", SqlDbType.Int).Value = SeizoenID;
var returnParameter = cmd.Parameters.Add("#Return", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
verbinding.Open();
cmd.ExecuteNonQuery();
var result = returnParameter.Value;
int returnwaarde = int.Parse(string.Format("{0}", result));
Console.WriteLine(returnwaarde);
string title = "Resultaat";
string message = "";
if (returnwaarde == 1)
{
message = "Uitslag succesvol toegevoegd";
MessageBox.Show(message, title);
}
verbinding.Close();
(SELECT ID FROM tblSnelsteRonde WHERE GrandPrixID = #intGrandPrixID AND SeizoenID = #intSeizoenID) This query of yours might return more than one value if there is more than one row in the table with the given #intGrandPrixID and #intSeizoenID
You can try something Like (SELECT Count(ID) FROM tblSnelsteRonde WHERE GrandPrixID = #intGrandPrixID AND SeizoenID = #intSeizoenID) == 0. If this is what you intend to do

Stored procedure returning result

I am creating a stored procedure to produce a list of items. The stored procedure returns a result and a return value. In my application that I am calling the stored procedures return the return value. How do I make it return the result?
This is my procedure:
CREATE PROCEDURE [AQB_RMS].[p_SO2EmailOverDue]
AS
(SELECT
CONVERT(CHAR(10), CheckDate, 101) AS ZSPDate,
Manufacturer, Model, SerialNumber, LocationName
FROM
[AQB_RMS].[SO2_Zsp] so
INNER JOIN
AQB_MON.[AQB_RMS].[Device] dev ON dev.DeviceID = so.DeviceID
INNER JOIN
AQB_MON.[AQB_RMS].[DeviceLocation] dl ON dev.DeviceID = dl.DeviceID
INNER JOIN
AQB_MON.[AQB_RMS].[Location] loc ON dl.LocationID = loc.LocationID
INNER JOIN
[AQB_RMS].[ManufacturerModel] mm ON dev.ManufacturerModelID = mm.ManufacturerModelID
INNER JOIN
[AQB_RMS].[Manufacturer] man ON mm.ManufacturerID = man.ManufacturerID
WHERE
CheckDate = (SELECT MAX(CheckDate) FROM [AQB_RMS].[SO2_Zsp]
WHERE DeviceID = so.DeviceID)
AND dl.EndDate IS NULL
AND (SELECT DATEDIFF(day, so.CheckDate, GetDate()) AS DayCount) > 14)
ORDER BY
CheckDate
RETURN
GO
The following is the return when I execute the stored procedure in SQL Server 2012
I am using the stored procedure to provide the results for the body of an email. I am using c#
static string Body()
{
//create a connection to the database
string ConnString = ConfigurationManager.ConnectionStrings["avdatauser"].ConnectionString;
StringBuilder sb = new StringBuilder();
using (SqlConnection con = new SqlConnection(ConnString))
{
con.Open();
SqlCommand cmd = new SqlCommand("AQB_RMS.p_SO2EmailNearDue", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
sb.Append("<strong>SO2 Analyzer ZSP due</strong>");
sb.Append("<br>");
sb.Append("<br>");
sb.Append("What do you want to say here to show these are the ones with a ZSP that are near due");
sb.Append("<br>");
sb.Append("<br>");
sb.Append(" " + cmd + " ");
con.Close();
}
return sb.ToString();
}

Error with SQL Server Stored Procedure & C#

I've been developing a stored procedure in order to get a register from a table so I built the following query to achieve this:
ALTER procedure [dbo].[procedure_odd]
#codSeccion int,
#NomDoce varchar(500),
#codMate varchar(500)
as
begin
declare #hora varchar(50);
set #hora = (
select b.man_nomhor
from ra_hpl_horarios_planificacion a
inner join ra_man_grp_hor b on a.hpl_codman = b.man_codigo
where a.hpl_codcil = 100
and a.hpl_codemp = (select emp_codigo from pla_emp_empleado
where emp_nombres_apellidos = #NomDoce)
and a.hpl_codmat = #codMate
and a.hpl_descripcion = #codSeccion)
return #hora
end
I've tested this query (ONLY the query not the stored procedure with the query) in my SQL Server console and it works just fine. The problem is when I call it from C# it doesn't work no matter what I try! Also I tried to develop a stored procedure with output parameter but with no result.
Also I've tried this other way(which works so good and fine!):
select b.man_nomhor
from ra_hpl_horarios_planificacion a
inner join ra_man_grp_hor b on a.hpl_codman = b.man_codigo
where a.hpl_codcil = 100
and a.hpl_codemp =
(select emp_codigo from pla_emp_empleado
where emp_nombres_apellidos = 'julio escobar')
and a.hpl_codmat = 'FONO-I'
and a.hpl_descripcion = 1;
Here is my code on C# (My 11000 solution):
public String horarios(int Seccion, string NomDocent, string CodMate)
{
cn.Open();
cmd.Connection = cn;
cmd.CommandText = "select b.man_nomhor from ra_hpl_horarios_planificacion
a inner join ra_man_grp_hor b on a.hpl_codman = b.man_codigo where
a.hpl_codcil = 100 and a.hpl_codemp =(select emp_codigo from
pla_emp_empleado where emp_nombres_apellidos = '" + NomDocent +
"') and a.hpl_codmat = '" + CodMate + "' and a.hpl_descripcion = '" + Seccion + "'";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
msj = dr[0].ToString();
}
}
cn.Close();
return msj;
}
When I run my Visual Studio it doesn't show any error at all but in the variable MSJ it set an empty STRING like this MSJ = "";
This must be really easy but it just that (believe) I've tried so hard to get to the solution with bno results, please help!
It looks like Seccion (and thus a.hpl_descripcion) are integers, but your query is placing apostrophes around it like a literal.
Try removing the apostrophes:
... + "' and a.hpl_descripcion = " + Seccion;
If that's indeed the issue, parameterizing your query can eliminate these kinds of mistakes:
cmd.CommandText = "... and a.hpl_codemp =(select emp_codigo from pla_emp_empleado where emp_nombres_apellidos = #NomDocent) and a.hpl_codmat = #CodMate and a.hpl_descripcion = #Seccion";
cmd.AddParameterWithValue("#NomDocent", NomDocent);
cmd.AddParameterWithValue("#CodMate", CodMate);
cmd.AddParameterWithValue("#Seccion, Seccion);
dr = cmd.ExecuteReader();
Few things:
if you want this to be a stored procedure, be sure to set command.CommandType = CommandType.StoredProcedure.
you do not need to call return or set a variable to return the text you have. instead, just have a select statement return the one field:
ALTER procedure [dbo].[procedure_odd]
#codSeccion int,
#NomDoce varchar(500),
#codMate varchar(500)
as
begin
select top 1 b.man_nomhor from ra_hpl_horarios_planificacion a inner join
ra_man_grp_hor b on a.hpl_codman = b.man_codigo where a.hpl_codcil = 100
and a.hpl_codemp = (select emp_codigo from pla_emp_empleado
where emp_nombres_apellidos = #NomDoce) and a.hpl_codmat = #codMate and
a.hpl_descripcion = #codSeccion)
END
once this is done, just execute the stored procedure with a dataReader, that will return your value. if you need more information, I can edit my answer to clarify.

C# SQL Query Producing Different Results than Management Studio

SELECT
wl.WatchListId, wl.Code, wl.[Description], wl.DateCreated,
wl.CreatedBy, wl.DateModified, wl.ModifiedBy,
wpi.ParameterExpression as IndividualExpression,
wpb.ParameterExpression as BusinessExpression,
wpd.ParameterExpression as DefaultExpression,
CASE
WHEN EXISTS(SELECT 1 FROM SourceWatchList
WHERE SourceId = #SourceId AND WatchListId = wl.WatchListId)
THEN 1 ELSE 0
END AS IsActive
FROM
[WatchList] wl
LEFT JOIN
SourceWatchList swl ON wl.WatchListId = swl.WatchListId AND swl.SourceId = #SourceId
LEFT JOIN
(SELECT
ParameterExpression, SourceId, WatchListId
FROM WatchListParameter
WHERE EntityType = 'INDIVIDUAL') wpi ON wpi.SourceId = #SourceId
AND wpi.WatchListId = wl.WatchListId
LEFT JOIN
(SELECT
ParameterExpression, SourceId, WatchListId
FROM WatchListParameter
WHERE EntityType = 'BUSINESS') wpb ON wpb.SourceId = #SourceId
AND wpb.WatchListId = wl.WatchListId
LEFT JOIN
(SELECT ParameterExpression, SourceId, WatchListId
FROM WatchListParameter
WHERE EntityType = 'DEFAULT') wpd ON wpd.SourceId = #SourceId
AND wpd.WatchListId = wl.WatchListId
WHERE
wl.IsActive = 1
I have the above query. Pretty simple.
Here's a snippet from SQL Server Management Studio table :
and from the debugger in Visual Studio :
The Visual Studio table has no data in the 3 Expression Columns while the Management Studio (correctly) does. Can any tell me why that is, and what steps I can take to resolve the issue?
I'm 100% sure I've used the same parameter between the two as well.
string sql = #"SELECT wl.WatchListId,wl.Code,wl.[Description],wl.DateCreated,
wl.CreatedBy,wl.DateModified,wl.ModifiedBy,
wpi.ParameterExpression as IndividualExpression,
wpb.ParameterExpression as BusinessExpression,
wpd.ParameterExpression as DefaultExpression,
CASE WHEN EXISTS(Select 1 FROM SourceWatchList
WHERE SourceId = #SourceId AND WatchListId = wl.WatchListId)
THEN 1 ELSE 0 END AS IsActive
FROM [WatchList] wl
LEFT JOIN SourceWatchList swl on wl.WatchListId = swl.WatchListId and swl.SourceId = #SourceId
LEFT JOIN (Select ParameterExpression, SourceId, WatchListId FROM WatchListParameter WHERE EntityType = 'INDIVIDUAL') wpi
ON wpi.SourceId = #SourceId AND wpi.WatchListId = wl.WatchListId
LEFT JOIN (Select ParameterExpression, SourceId, WatchListId FROM WatchListParameter WHERE EntityType = 'BUSINESS') wpb
ON wpb.SourceId = #SourceId AND wpb.WatchListId = wl.WatchListId
LEFT JOIN (Select ParameterExpression, SourceId, WatchListId FROM WatchListParameter WHERE EntityType = 'DEFAULT') wpd
ON wpd.SourceId = #SourceId AND wpd.WatchListId = wl.WatchListId
where wl.IsActive = 1";
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["WatchListCompliance"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#SourceId", SourceId);
DataTable dt = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(dt);
}
This might be a problem with types and equality. You can try using SqlDataType when you define the parameters on the sqlcommand. When you use addwithvalue without declaring a type it could be selecting the wrong type. Then you should use the type you declared in the sql expression.
cmd.Parameters.Add("#SourceId", SqlDbType.VarChar, 20);
cmd.Parameters["#SourceId"].Value = SourceId;
Wild guess: are you sure your session is configured the same way? Especially the SET ANSI_NULLS option, which changes how comparison behaves with regard to null values.
It is worth noting that some databases may have unusual default values, but some clients (e.g. ADO.NET) explicitely define their own values for the session when they connect, even if you don't ask them to.

input parameter to mysql syntax on C#

I try to input value but #numVal doest not work ( on the line begin with arr[10] )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MySqlConnection conDatabase = new MySqlConnection("Data Source=localhost;" +
"Persist Security Info=yes;" +
"UserId=tee; PWD=t5794849; database=ph3;");
conDatabase.Open();
// MySqlCommand cmdDatabase = new MySqlCommand("DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc;", conDatabase);
Console.WriteLine("Enter username");
string input = Console.ReadLine();
try
{
int numVal = Convert.ToInt16(input);
}
catch (FormatException )
{
Console.WriteLine("Input string is not a sequence of digits.");
}
catch (OverflowException )
{
Console.WriteLine("The number cannot fit in an Int32.");
}
string[] arr = new string[11];
arr[0] = "UPDATE `member` SET `amphurecode`= SUBSTRING(member.own,3,4)";
arr[1] = "UPDATE `member` SET `provincecode`= SUBSTRING(member.own,3,2)";
arr[2] = "DROP TABLE IF EXISTS `q_mem_tim`; create table q_mem_tim as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.novote, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE";
arr[3] = "DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc";
arr[4] = "DROP TABLE IF EXISTS `q_mem_hno` ; create table q_mem_hno as select member.Hno, member.Moo, member.tambol, COUNT( member.Hno ) AS cntHno, COUNT(DISTINCT member.Ssurname) as NoSur FROM member GROUP BY member.Hno, member.Moo, member.tambol ORDER BY cntHno DESC ";
arr[5] = "DROP TABLE IF EXISTS `q_pro_ori`; create table q_pro_ori as Select member.provincecode, count(*) As cnt From member Group By member.provincecode Order By cnt Desc ";
arr[6] = "DROP TABLE IF EXISTS `q_am_ori`; create table q_am_ori as Select member.amphurecode, member.provincecode, count(*) As cnt From member Group By member.amphurecode, member.provincecode Order By cnt Desc ";
arr[7] = "DROP TABLE IF EXISTS `Sur_Hno_`; create table Sur_Hno_ as SELECT count( * ) , Ssurname, q_mem_tim.Hno, q_mem_tim.Moo, q_mem_tim.tambol FROM q_mem_tim GROUP BY q_mem_tim.Ssurname, q_mem_tim.Hno, q_mem_tim.Moo, q_mem_tim.tambol ORDER BY count( * ) DESC";
arr[8] = "DROP TABLE IF EXISTS `q_dup_own`; create table q_dup_own as SELECT Count(*) as n ,member.own FROM member GROUP BY member.own order by n DESC ";
// arr[9] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, member.fathercode , member.mathercode, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d ,member.inputstaf FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE WHERE DAYOFYEAR(member.dateofbirth)-DAYOFYEAR(NOW()) < 30 and DAYOFYEAR(member.dateofbirth)-DAYOFYEAR(NOW()) > -1 order by DAYOFYEAR(member.dateofbirth)";
arr[9] = "ALTER TABLE `q_mem_tim` ADD `agec` VARCHAR( 10 ) NULL ";
// arr[10] = "UPDATE q_mem_birth SET agec = CASE WHEN y < 10 THEN 'ด' WHEN y > 10 and y < 20 and Sex='ญ' THEN 'วญ' WHEN y > 10 and y < 20 and Sex='ช' THEN 'วช' ELSE 'ผญ' END";
arr[10] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT q_mem_tim.idmember,q_mem_tim.own,q_mem_tim.PROVINCE_NAME,q_mem_tim.AMPHUR_NAME,q_mem_tim.novote,q_mem_tim.Sname,q_mem_tim.Ssurname,q_mem_tim.Hno,q_mem_tim.Moo,q_mem_tim.Sex,q_mem_tim.tambol,q_mem_tim.dateofbirth,q_mem_tim.migratedate,q_mem_tim.y,q_mem_tim.d,q_mem_tim.agec FROM q_mem_tim where q_mem_tim.dateofbirth is not null and q_mem_tim.dateofbirth != '00000000' and day(q_mem_tim.dateofbirth) != '00' and day(q_mem_tim.dateofbirth) > 0 and day(q_mem_tim.dateofbirth) < 11 and month(q_mem_tim.dateofbirth) != '00' and month(q_mem_tim.dateofbirth) = #numVal order by tambol,Moo, month(dateofbirth),day(dateofbirth) ";
foreach (string s in arr)
{
Console.WriteLine(s);
MySqlCommand cmdDbase = new MySqlCommand((s), conDatabase);
cmdDbase.CommandTimeout = 500;
cmdDbase.ExecuteNonQuery();
}
conDatabase.Close();
}
}
}
1)Truncate the tables; don't drop them and remake them because when you drop them you have to do the indexes and add the Primary Keys again.
using(var cm = _dbConnection.CreateCommand())
{
cm.CommandText = #"Truncate Table Table";
cm.CommandType = CommandType.Text;
cm.ExecuteNonQuery();
}
2)Don't forget the # symbol; it helps with anything SQL:
using(var cm = _dbConnection.CreateCommand())
{
cm.CommandText = #"Select *
From table
Where Id = #Id";
cm.CommandType = CommandType.Text;
cm.Parameter.AddWithValue("Id", id);
cm.ExecuteNonQuery();
}
I know you're not doing it this way and you're using a string array (just put a foreach loop outside the using statement and replace the cm.CommandText value with the string's value) but with the examples it should help you or at least give you some ideas.
You need to add a MySqlParameter to the command named numVal.

Categories

Resources