I'm looking for a way to check if a customer ID exists in the Customer table, and if it exists in the table being queried.
If it doesn't exist in the Customer table or it already exists in the table being queried (or it is in Customer but also already exists in table in question) then I don't want it to insert the data.
I thought that maybe I could do if..if code - more code - if..if code - else, but that didn't work. Here is what I mean:
cmd.CommandText = "SELECT COUNT(*) FROM Customer WHERE customer_id = #cid";
cmd.Connection = conn;
conn.Open();
int count = (int)cmd.ExecuteScalar();
conn.Close();
if (count < 1)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID does not exist and will not be submitted')</script>");
tb0.Focus();
}
cmd.CommandText = "SELECT COUNT(*) FROM table_name WHERE customer_id = #cid";
cmd.Connection = conn;
conn.Open();
int count2 = (int)cmd.ExecuteScalar();
conn.Close();
if(count2 > 0)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID already exists in table_name and will not be submitted')</script>");
tb0.Focus();
}
else
{
cmd.CommandText = "INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5)";
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close(); }
Unless I comment one out then the second one will work and the first I guess gets ignored? I'm not really sure but they both work if the other is commented out
Errors from answer:
Incorrect syntax near the keyword 'THEN'.
Incorrect syntax near the keyword 'ELSE'.
Incorrect syntax near the keyword 'THEN'.
Incorrect syntax near the keyword 'ELSE'.
#"IF NOT EXISTS (SELECT * FROM Customer WHERE customer_id = #cid) THEN BEGIN
SELECT 'NO_CUSTOMER' as Result
END ELSE IF EXISTS (SELECT * FROM table_name WHERE customer_id = #cid) THEN BEGIN
SELECT 'ALREADY_RECORD' as Result
END ELSE BEGIN
INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5);
SELECT 'SUCCESS' AS Result;
END";
Why not try something a bit simpler, like this?
cmd = conn.CreateCommand();
cmd.CommandText =
#"IF NOT EXISTS (SELECT * FROM Customer WHERE customer_id = #cid) THEN BEGIN
SELECT 'NO_CUSTOMER' as Result
END ELSE IF EXISTS (SELECT * FROM table_name WHERE customer_id = #cid) THEN BEGIN
SELECT 'ALREADY_RECORD' as Result
END ELSE BEGIN
INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5);
SELECT 'SUCCESS' AS Result;
END";
cmd.Parameters.AddWithValue(#cid, ...);
cmd.Parameters.AddWithValue(#val1, ...);
cmd.Parameters.AddWithValue(#val2, ...);
...
switch((string)cmd.ExecuteScalar()) {
case "NO_CUSTOMER":
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID does not exist and will not be submitted')</script>");
tb0.Focus();
break;
case "ALREADY_RECORD":
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID already exists in table_name and will not be submitted')</script>");
tb0.Focus();
break;
}
Related
I get the error "42883: operator does not exist: integer =# integer" Npgsql.PostgresException
when trying to pass parameters to a DO block:
var cmd = new NpgsqlCommand();
cmd.CommandText =
#"DO $$
BEGIN
IF EXISTS (SELECT id FROM pub.table1 WHERE id = #id) THEN
UPDATE pub.table1
SET Field1 = #Field1
,Field2 = #Field2
WHERE id = #id;
ELSE
INSERT INTO pub.table1 (id, Field1, Field2)
VALUES (#id, #Field1, #Field2);
END IF;
END $$;";
cmd.Parameters.AddWithValue("#id", 1);
cmd.Parameters.AddWithValue("#Field1", "text");
cmd.Parameters.AddWithValue("#Field2", "text2");
Otherwise connection to postgres works and also (classic) queries work when passing parameters; e.g.:
cmd.CommandText = #"SELECT * FROM pub.table1 WHERE id = #id;";
Is it not possible to pass parameters to a "DO" block or am I missing something?
Thank you.
M
Initially I had commandtext defined in my ssis C# script task which counted the number of rows from table A. Now I need to add two more commandtext which counts the rows from table b and C respectively as I need to include the output of that query in my customized email.
try
{
dbConnection.Open();
if (dbConnection.State == ConnectionState.Open)
{
OleDbCommand dbCommand = dbConnection.CreateCommand();
dbCommand.CommandType = CommandType.Text;
dbCommand.CommandText = "select count(*) as Total_Source from [dbo].A";
dbCommand.CommandText = "select count(*) as Total_Destination from [dbo].B";
dbCommand.CommandText = "select count(*) as Total_Blank from [dbo].C where ColumnA = ''";
OleDbDataReader dbReader = dbCommand.ExecuteReader();
if (dbReader.HasRows)
dtResults.Load(dbReader);
string theSum = dtResults.Rows[0]["Total_Source"].ToString();
string theSum1 = dtResults.Rows[0]["Total_Destination"].ToString();
//string theSum2 = dtResults.Rows[0]["Count_Blank"].ToString();
I believe I need to define command text for table B and C (which is incorrect in the above script) but I am unaware how to do.
Appreciate any help!
Store the counts in variables and return those in a select - make this your SQL statement:
DECLARE #total_Source AS INT;
DECLARE #total_Destination AS INT;
DECLARE #total_Blank AS INT;
SELECT #total_Source=Count(*) FROM [dbo].A;
SELECT #total_Destination=Count(*) FROM [dbo].B;
SELECT #total_Blank=Count(*) FROM [dbo].C WHERE ColumnA = ''";
SELECT #total_Source AS Total_Source, #total_Destination AS Total_Destination, #total_Blank AS Total_Blank
I haven't tried it, but I think that if CommandText is a string property, you are overwritting it on each sentence you use the = operator.
You could try this:
//...
OleDbCommand dbCommand = dbConnection.CreateCommand();
dbCommand.CommandType = CommandType.Text;
var sb = new System.Text.StringBuilder();
sb.Append("select count(*) as Total_Source from [dbo].A;"); // Notice semicolon at the end of the string.
sb.Append("select count(*) as Total_Destination from [dbo].B;");
sb.Append("select count(*) as Total_Blank from [dbo].C where ColumnA = '';");
dbCommand.CommandText = sb.ToString();
OleDbDataReader dbReader = dbCommand.ExecuteReader();
//...
I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)
I try to update my MYSQL table with this code.
string sqlquery = String.Format("if exists(select 1 from orders where id =\" {0}\" ) begin update orders set customer_id = \"{1}\", total = \"{2}\", fio = \"{3}\", adress =\" {4}\" where id = \"{0}\" end else begin insert into orders (id, customer_id, total, fio, adress) values(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\") end", id, customer_id, total, fio, adress);
MySqlCommand addCommand2 = new MySqlCommand(sqlquery.ToString(), connection);
addCommand2.ExecuteNonQuery();
But I have this error
Additional information: 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 'if exists(select 1 from orders where id = 1913 ) begin update orders set custome' at line 1
Database
What wrong in query?
Thank's for help!
why dont you do it in more elegant way:Something like.:
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "if exists(select 1 from orders where id =#id)
begin
update orders set customer_id = #customer_id, total = #total, fio = #fio, adress =#adress where id = #id end
else
begin insert into orders (id, customer_id, total, fio, adress) values(#id, #customer_id, #total, #fio,#adress) end";
command.Parameters.AddWithValue("#id", val1);
command.Parameters.AddWithValue("#customer_id", val2);
command.Parameters.AddWithValue("#total", val3);
command.Parameters.AddWithValue("#fio", val4);
command.Parameters.AddWithValue("#adress", val5);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
I have a stored procedure on my server that inserts some parameters and returns the ID that was inserted. I am writing a form to do this easily but I cannot seem to get the parameter which is passed back.
To save you doing a whole bunch of possibly pointless reading, it's probably better to just pay attention to my C# code and let me know what I need to do in order to pass parameters and get one in return.
C# Default.aspx
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("#FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
connection.Open();
int ID = command.ExecuteNonQuery();
connection.Close();
SQL aStoredProc
IF EXISTS(SELECT * FROM aTable WHERE ID = #ID)
-- User exists, update details
BEGIN
BEGIN TRAN
UPDATE aTable
SET
FirstName = #FirstName,
SurName = #SurName,
LastUpdate = GetDate()
WHERE ID = #ID
IF (##Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
ELSE
-- New user
BEGIN
BEGIN TRAN
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
#FirstName,
#SurName,
#LastUpdate
)
SELECT #ID = ##IDENTITY
IF (##Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
The parameter #ID is listed in the stored proc as:
#ID (int, Input/Output, No default)
and proc has 'Return integer'. This used to work fine with a VBA solution prior to a SQL Server 2005 upgrade.
Thanks in advance.
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("#FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
SqlParameter ParamId = cmd.Parameters.Add( "#Id", SqlDbType.Int);
ParamId.Direction = ParameterDirection.InputOutput;
command.Parameter.Add(ParamId);
connection.Open();
command.ExecuteNonQuery();
int ID = ParamId.Value;
connection.Close();
you have to add output paramter in Parameter collection.
Read Value like above.
You have an error in your SQL, it should look like this:
INSERT aTable (FirstName,SurName,LastUpdate)
VALUES (#FirstName, #SurName, GetDate() )
Not like this:
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
#FirstName,
#SurName,
#LastUpdate
)