Check if exist each one row Separately and run the same code - c#

I have two tables i want to check if exist Barcode from first Table to Second. But i want run the code only for the first row. When it will end then to run the same code for the second row and making the same for rest of my rows till it will end.
Here is an example of my code which i want to use: But How will i run the code for each row separately.Starting with first then with second,third and go on.
Code: For SQL
IF EXISTS ( SELECT Barcode FROM Table_1 where barcode = (select barcode from Table_2)
BEGIN
update Table_2 set Name = (select Name from Table_1)
END
ELSE
BEGIN
insert into Table_2 (Barcode,Name) (select Barcode,name from Table1)
END
Code: For C#
System.Data.SqlClient.SqlCommand CheckNone = new System.Data.SqlClient.SqlCommand("IF EXISTS( SELECT Barcode FROM Table_1 where barcode = (select barcode from Table_2) SELECT 1 ELSE SELECT 0", con);
con.Open();
var result = (int)CheckNone.ExecuteScalar();
if (result == 0)
{
SqlCommand cmd = new SqlCommand("insert into Table_2 (Barcode,Name) (select Barcode,name from Table1)",con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
SqlCommand cmd = new SqlCommand("update Table_2 set Name = (select Name from Table_1)",con);
cmd.ExecuteNonQuery();
con.Close();
}
}

It sounds like you just need to update the Name in Table 2 for rows with matching Barcode values in Table 1. You can to that for the entire table in teo queries:
UPDATE t2
SET Name = t1.Name
FROM Table2 t2
INNER JOIN Table1 t1
ON t2.Barcode = t1.Barcode
INSERT INTO Table2
(Barcode, Name)
SELECT Barcode, Name
FROM Table1
WHERE Barcode NOT IN
(SELECT Barcode FROM Table2)
If you really want to update one row at a time, then just add WHERE Barcode = #barcode to your SELECT queries and pass the paramater value to the Command in C#. Note however that it will be MUCH slower than doing it all at once.

Related

Only insert data into a database if it doesn't exist already

I'm trying to work on a code that allows me to only insert records that have a different ID; if the same ID already exists in the database then the record shouldn't be inserted.
My SQL code is this:
SqlCommand cmd = new SqlCommand("insert into User(UserId,Name,Profession) values(#UserId,#Name,#Profession) WHERE NOT EXISTS (Select UserId From User where UserId = #UserId)", con);
But it doesn't work and when I try this, nothing gets added to the database.
How do I correct this query?
Thank you,
Instead of :
insert into User(UserId,Name,Profession)
values(#UserId,#Name,#Profession)
WHERE NOT EXISTS (Select UserId From User where UserId = #UserId)
use this query :
insert into User(UserId,Name,Profession)
select #UserId, #Name, #Profession
where not exists (Select UserId From User where UserId = #UserId)
Explanation : AFAIK the insert command can't combine a VALUES and a WHERE clause. But instead of directly supplying the values (using the VALUES clause), you can define a SELECT to indicate the values to insert. And on that SELECT you can now use filters, joins, etc. ..., so you can define there your filter checking that the row doesn't still exists.
Try this:
SqlCommand cmd = new SqlCommand("IF NOT EXISTS (Select UserId From User where UserId = #UserId) insert into User(UserId,Name,Profession) values(#UserId,#Name,#Profession) ", con);
This is SQL query to achieve the same.
IF NOT EXISTS (Select UserId From User where UserId = #UserId
insert into User(UserId,Name,Profession) values(#UserId,#Name,#Profession)
You can use a MERGE statement :
https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql
Or using CTE : https://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql

Create a temporary table and then Select

I have the following problem in an WPF application written in c#. I need to create some temporary tables on an sql server, do some joins from within the app an then select from the joined table. In the statistical language R I simply create two SQL Queries (one containing the #tables and one with the final select statement from a merge of several #tables) and execute them one after another. Doing the query in just one Query only returns NULL after the #temp tables have been created.
This is SQL statement #1:
DECLARE #from_time Date;
DECLARE #to_time Date;
CREATE TABLE #temp1
(
person_id float,
first_name varchar(100),
othercols...
)
INSERT INTO #temp1
SELECT DISTINCT
person_id, first_name, ...
FROM
campus.v_exam_registration_context context
FULL JOIN
campus.v_exam_timetable time
ON
CAST(context.examination_date AS DATETIME) = time.timetable_date
AND
context.examination_time_from = time.time_from
AND
context.examination_time_to = time.time_to
CREATE TABLE #temp2
(
exam_event_id float,
person_id float,
othercols...
)
INSERT INTO #temp2
SELECT DISTINCT
exam_event_id, person_id, excused, excused_reason, missed, modify_date, study_id, study_name,
person_exam_id, exam_in_course_id, subject, subject_unicode, personal_exam_no, exam_points, grade_description
FROM
campus.v_person_exam exam
WHERE
exam.person_id
IN
(
SELECT
#temp1.person_id
FROM
#temp1
WHERE
#temp1.attempt_counter > 1
AND
#temp1.timetable_date > #from_time
AND
#temp1.timetable_date < #to_time
)
CREATE TABLE #temp3
(
person_id float,
first_name varchar(100),
)
INSERT INTO #temp3
SELECT
#temp2.person_id, first_name, last_name, matriculation_number, attempt_counter, timetable_date, examination_date, semester, course_number, course_name,
exam_name, exam_type, component_name, course_area, module_number, module_name, credits,
FROM
#temp2
LEFT JOIN
#temp1
ON
#temp2.person_id = #temp1.person_id
AND
#temp2.exam_event_id = #temp1.exam_event_id
WHERE
#temp1.course_name IS NOT NULL
And this is #2:
SELECT DISTINCT T1.*
FROM
#temp3 T1
INNER JOIN
(
SELECT *
FROM
#temp3
WHERE
#temp3.attempt_counter > 1
AND
#temp3.exam_points > 4
AND
#temp3.timetable_date > #from_time
AND
#temp3.timetable_date < #from_time
) as T2
ON
T1.person_id = T2.person_id
AND
T1.exam_name = T2.exam_name
ORDER BY T1.last_name ASC, T1.course_name DESC, T1.timetable_date ASC
But now I'm required to translate the R Script into a standalone exe-file.
Here is my code block in c#:
private void queryButton_Click(object sender, RoutedEventArgs e)
{
List<Student> temp = new List<Student>();
string pass = #pass_box.Password;
string dsn = "CampusNet";
String ConnectionString =
"DSN=" + dsn + ";" +
"UID=" + uid + ";" +
"PWD=" + pass;
OdbcConnection conn = new OdbcConnection(ConnectionString);
using (conn)
{
if (conn.State.ToString() == "Open")
{
conn.Close();
}
try
{
conn.Open();
var command = new OdbcCommand(sqlcommand, conn); \\sqlcommand is read from a textfile
command.Parameters.AddWithValue("#from_time", from_time);
command.Parameters.AddWithValue("#to_time", to_time);
command.CommandTimeout = 120;
var resultCommand = command.ExecuteNonQuery();
var query = new OdbcCommand(sqlquery, conn); \\sqlquery is read from a textfile
query.Parameters.AddWithValue("#from_time", from_time);
query.Parameters.AddWithValue("#to_time", to_time);
var resultQuery = query.ExecuteReader();
Results_Box.AppendText(resultQuery.HasRows.ToString());
while (resultQuery.Read())
{
temp.Add(new Student{
name = !result.IsDBNull(3) ? result.GetString(3) : null
});
Results_Box.AppendText("Test"); \\only for testing purposes, works if I select from existing table
}
resultQuery.Close();
results = temp;
Results_Box.Document.Blocks.Add(new Paragraph(
new Run("There are " + temp.Count().ToString() + " Hits")));
System.Windows.Forms.MessageBox.Show("Connected");
conn.Close();
}
catch (Exception E)
{
Results_Box.Document.Blocks.Add(new Paragraph(new Run("Connection failed")));
Results_Box.Document.Blocks.Add(new Paragraph(new Run(E.ToString())));
}
}
}
I'm new to c#, so it seems that the first query is executed but deleted immediately afterwards and the second select statement returns 0 hits. If I select from non-temporary tables everything works fine. Since the first query has a duration approximately equal to the respective R-Query (25 sec), I suspect that the first one is correctly executed, but immediately deleted or the second query starts before the first is finished. Creating one combined query does not work neither in R nor in c#. I would like to stick to temporary tables rather than using ##tables, if possible.
Is there a special method to use for creating temp tables in c#? conn.open() is open during the whole runtime of using (conn){...} ?

Select more columns with MAX function in SQLCE

Need to find max value of id, and by this value I need to read value of others column. But it is influenced by another column type.
I used this sql command:
"SELECT * FROM Table WHERE id = (SELECT MAX(id) FROM Table WHERE type = 1)"
ID column is bigint type, and type is nchar. I tried use it with type = '1' too, but same problem.
Error is after "id = " section
Thanks for reply
EDIT:
SqlCeCommand com = new SqlCeCommand();
if (LocalType == '1') { com = new SqlCeCommand("SELECT req_id FROM Requisition WHERE id = (SELECT MAX(id) FROM Requisition WHERE type = 1)", con); }
else if (LocalType == '2') { com = new SqlCeCommand("SELECT req_id FROM Requisition WHERE id = (SELECT MAX(b.id) FROM Requisition AS b WHERE b.type <> 1)", con); }
using (com)
{
SqlCeDataReader reader = com.ExecuteReader();
}
The easiest way to do this is using top. If this is your real code, then you need to "escape" the word "table" because it is a reserved word:
select top 1 t.*
from [table] t
where type = '1'
order by id desc
Try naming the tables:
SELECT *
FROM Table AS a
WHERE id = (SELECT MAX(b.id) FROM Table AS b WHERE b.type = 1)
After a while on google, find that SQLCE in version 3.5 support SELECT TOP expression, but with difference with formating. It must be write with brackets
SELECT TOP(1) * FROM MyTable

asp.net multiple table update statement

I need to turn this query into an update statement. I will have to update the values from fields. Everything is already in place but the update statement.
Here is the select version of the query:
SELECT i.GoLiveDate, i.FirstBonusRun, i.TechFName, i.TechLName, i.TechEmail, i.TechPhone, i.WebISPFName, i.WebISPLName,
i.WebISPEmail, i.WebISPPhone, i.FullFillFName, i.FullFillLName, i.FullFillEmail, i.FullFillPhone, d.FName,
d.LName, d.HomePhone, d.Email
FROM NC_Information i
INNER JOIN Distributor d
ON d.DistID = i.ClientID
WHERE clientID = #value
Is it possible to update two different tables from within the same query?
Here is the code I have so far:
public void Update (int ClientID)
{
using ( var conn = new SqlConnection( GeneralFunctions.GetConnectionString() ) )
using ( var cmd = conn.CreateCommand() )
{
conn.Open();
cmd.CommandText =
#"SELECT i.GoLiveDate, i.FirstBonusRun, i.TechFName, i.TechLName, i.TechEmail, i.TechPhone, i.WebISPFName, i.WebISPLName,
i.WebISPEmail, i.WebISPPhone, i.FullFillFName, i.FullFillLName, i.FullFillEmail, i.FullFillPhone, d.FName,
d.LName, d.HomePhone, d.Email
FROM NC_Information i
INNER JOIN Distributor d
ON d.DistID = i.ClientID
WHERE clientID = #value";
cmd.Parameters.AddWithValue( "#value", ClientID );
cmd.ExecuteNonQuery();
}
}
You can't update multiple tables in one statement, but you can use a transaction to make sure that the updates are contingent upon one another:
BEGIN TRANSACTION
UPDATE SomeTable
SET SomeColumn = 'Foo'
WHERE SomeID = 123
UPDATE AnotherTable
SET AnotherColumn = 'Bar'
WHERE AnotherID = 456
COMMIT
I think, you cannot directly do the update on two tables. But you can Optimize the query.
How?
OUTPUT keyword in Insert/Update/Delete Statement
The first Update Statement's Select Data(filtered data) can be reused using the below mentioned example.
CREATE TABLE #table1
(
id INT,
employee VARCHAR(32)
)
go
INSERT INTO #table1 VALUES
(1, 'name1')
,(2, 'name2')
,(3, 'name3')
,(4, 'name4');
GO
DECLARE #GuestTable TABLE
(
id INT,
employee VARCHAR(32)
);
update #table1
Set id = 33
OUTPUT inserted.* INTO #GuestTable
Where id = 3
The Data in the '#GuestTable' Table is filtered data and can be
reused.
select * from #GuestTable
drop table #table1
Alternatively, you can create a dataset with two datatables, and let the tableadaptermanager manage the updates.

How can I count the number of columns in a MySQL table using C#?

I can select the number of rows returned by a query when I select everything by doing the following:
SELECT Count(*) FROM `foo`.`bar`;
However, I now want to select how many columns are returned. Is there an easy way to do this?
Use the information_schema database.
SELECT
COUNT(COLUMN_NAME) AS numcols
FROM COLUMNS
WHERE
TABLE_NAME = 'bar'
AND TABLE_SCHEMA = 'foo'
To put the two together, use:
SELECT
(SELECT COUNT(*) FROM foo.bar) AS numrows,
(SELECT
COUNT(COLUMN_NAME) AS numcols
FROM COLUMNS
WHERE
TABLE_NAME = 'bar'
AND TABLE_SCHEMA = 'foo'
) AS numcols
DESCRIBE someTable and then mysql_count_rows() on the result.
Since the question has to do with C#, I think this should work - but I haven't done C# in a long time.
MySqlConnection connection = new MySqlConnection(#...);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "DESCRIBE sometable";
connection.Open();
Reader = command.ExecuteReader();
Reader.FieldCount # this has the count of rows, and hence columns
If your table mydb.mytable is MyISAM, the following should work well:
SELECT
row_count,column_count
FROM
(
SELECT table_rows row_count
FROM information_schema.tables
WHERE table_schema = 'mydb'
AND table_name = 'mytable'
) rowcount,
(
SELECT MAX(ordinal_position) column_count
FROM information_schema.columns
WHERE table_schema = 'mydb'
AND table_name = 'mytable'
) columncount
;

Categories