1

I'm trying to build a query that can give me the different rows between two tables.

Here is my code:

try
{
    string searchquery = "SELECT* FROM NewList EXCEPT SELECT* FROM Restaurants UNION All";

    SqlCommand searchcom = new SqlCommand(searchquery, connection);
    SqlDataAdapter da = new SqlDataAdapter(searchcom);
    DataSet ds = new DataSet();

    connection.Open();
    da.Fill(ds);

    dataGridView1.DataSource = ds.Tables[0];
    connection.Close();
}
catch (Exception er)
{
    Debug.WriteLine(er.Message);
    return;
}

I get the following error:

Incorrect syntax near 'All'.

What is the correct way/syntax to use Union All in SqlCommand class? I've tried to put it it my query string in too many ways but it's giving me the same error every time. How can I implement it in my search query with correct syntax ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bora
  • 39
  • 6
  • 1
    "What is the correct way/syntax to use Union All ?" isn't it? you just wrote invalid SQL query, and in the example, it shows how to write a valid query using UNION ALL – styx Dec 31 '19 at 07:41
  • What is the correct way/syntax to use Union All in SqlCommand query string. That's the question. – Bora Dec 31 '19 at 07:46
  • Are you trying to find the rows in one table that are not present in the other? – AsheraH Dec 31 '19 at 07:54
  • @AsheraH yes. There are nearly 26000 rows in "NewList" and 25000 rows in "Restaurants". I'm trying to get that new 1000 row to a datagridview – Bora Dec 31 '19 at 07:58
  • remove the `UNION ALL` from your query – Squirrel Dec 31 '19 at 08:55

2 Answers2

2

Your query is incorrect from UNION ALL on.

You can try it like this:

string searchquery = "SELECT * FROM NewList UNION ALL SELECT * FROM Restaurants ";

However, you need to be aware that:

  1. It does not remove duplicate rows between the various SELECT statements (all rows are returned)
  2. Each SELECT statement within the UNION ALL must have the same number of columns in the result sets with similar data types

Read here for more details.

Updated

You should use EXCEPT instead of UNION ALL if you want to get rows in one table that are not present in the other one.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0
Select Checking.RestID, FROM 
(SELECT RestID FROM NewList EXCEPT Select RestID from Restaurants) as Checking
LEFT JOIN NewList ON Checking.RestID = NewList.RestID 

this worked, thanks to anyone !

Bora
  • 39
  • 6