SQL Select Multiple table at onces - sql

I was thinking is there a query that can select many table at once?. Not using a JOINS. I tried to research about it but all I got is
SELECT * FROM Table WHERE ID IN (parameter1,parameter2);
I tried this kind of query
select * from Table Table1,Table2
but the result is getting from the Table1 only.
All tables are not it relation with each other so it means they are different table to each. What I am trying to do here is I will check the tables if there is a data on it or not. What I was using is query it all one-by-one using
select * from Table
again and again. Hope this will explain it.

For combined Tables as an output:
UNION
To allow duplicate values, use:
UNION ALL
SELECT * FROM table1
UNION
SELECT * FROM table2
For separated Tables as an output:
DataSet
DataSet dataSet = new DataSet();
DataTable table1 = new DataTable("table1");
DataTable table2 = new DataTable("table2");
dataSet.Tables.Add(table1);
dataSet.Tables.Add(table2);
using(SqlCommand cmd = new SqlCommand("SELECT * FROM table1;SELECT * from table2", con))
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
dataSet.Load(dr, LoadOption.OverwriteChanges, table1, table2);
}
}
Now you can work with the DataSet's Tables like this (msdn documentation):
private void PrintRows(DataSet dataSet)
{
// For each table in the DataSet, print the row values.
foreach(DataTable table in dataSet.Tables)
{
foreach(DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
}
}

Take a look at SQL command UNION. Then you can make something like
SELECT * FROM table1
UNION
SELECT * FROM table2;

Related

How to Improve - Multiple inserts with different Ids using multiple OledbConnections

currently the system is creating multiples OledbConnections and the process is taking a long time to finish, it sums up to this:
C# code:
Select all person from table A.
FOR EACH person: Do a SELECT to see if ID 'x' from table A exists in table B.
FOR EACH person: INSERT with the ID from table A or a new ID (if that ID already exists in table B)
All these INSERTS are creating a new OledbConnection for each person, and for example 3k persons, it is taking too long.
It would be easier if I didn't have to deal with the IDs, but I'm not finding a good way to do this with VFP.
is that a way to Bulk INSERT this, or improve the performance?
if id in table2 is autonumber:
if exists(select * from table2 where id = idtable1)
insert into table2(field1,field2...
else
insert into table2(ID,field1,field2...
I don't understand why you need to use multiple OleDbConnections for this. A single connection would do:
string sql = #"insert into tableB (id, f1, f2, f3)
select getNextId('tableB'), f1, f2, f3
from tableA
where exists (select * from tableA where tableA.id = tableB.id)";
using (OleDbConnection cn = new OleDbConnection(#"Provider=VFPOLEDB;Data Source=c:\MyDataFolder"))
using (OleDbCommand cmd = new OleDbCommand(sql, cn))
{
cn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = #"insert into tableB (id, f1, f2, f3)
select id, f1, f2, f3
from tableA
where not exists (select * from tableA where tableA.id = tableB.id)";
cmd.ExecuteNonQuery();
cn.Close();
}
The SQLs used may not be right, because from your definition, it is not clear what you are really trying to do.
And BTW, you are not telling about the version, if Foxpro tables mean VFP tables then there is autoinc int field (but not necessary you can always have your own getNextId function as in the sample).

How do I create a query to extract differences between two tables that contain null values?

I am writing a query that extracts the differences between a new table and an old table.
SELECT New.Entity, New.Type, New.Address, New.Country
FROM tbl_EntityList_New As New
WHERE NOT EXISTS (SELECT * FROM tbl_EntityList_Old as Old
WHERE New.Entity = Old.Entity
AND New.Address = Old.Address);
However, the query seems to mistakenly return blank addresses as a difference. To combat this, I added another portion to the first WHERE clause as so:
SELECT New.Entity, New.Type, New.Address, New.Country
FROM tbl_EntityList_New As New
WHERE NOT EXISTS (SELECT * FROM tbl_EntityList_Old as Old
WHERE New.Entity = Old.Entity
AND New.Address = Old.Address)
AND New.Address Is Not Null;
However, new records with blank addresses will be excluded from this query, and I have no influence over how users enter in their new records.
How can I amend my SQL to extract the differences I need? Thanks for your help in advance!
I think you are looking for:
SELECT New.Entity, New.Type, New.Address, New.Country
FROM tbl_EntityList_New As New
WHERE NOT EXISTS (SELECT 1
FROM tbl_EntityList_Old as Old
WHERE New.Entity = Old.Entity AND
( New.Address = Old.Address OR
New.Address IS NULL AND Old.Address IS NULL
);

I need to get a distinct list based on a column in SQL

var sqlStatement = string.Format("select * from CardDecks where deckid = {0}", id);
var getcardid = db.CardDecks.SqlQuery(sqlStatement).ToList();
var getDistinct = getcardid.Distinct().ToList();
What I expect from this code is for the last list to only pull distinct values but it still pulls duplicates. I need for it to only pull back the list with unique values based on cardid. What am I missing?
I changed the SQL statement to this and it works:
List<CardDeck> distictList = getcardid.GroupBy(p => p.CardID).Select(g => g.First()).ToList();
You could write your query like this:
select distinct column1, column2, column3 from CardDecks where deckid = {0}
... where column1, column2, column3 are the columns that you want to show.

Sphinx Multiple Sources - One Index

Assuming that I have a database with 20 some tables, all with the same schema, how do I create one index for all tables?
If I have ONE index per table, the search works just fine.
I successfully created ONE index for the 20 tables, but every search returns the first record of the first table.
Index conf:
index all_table_index
{
type = plain
source = TABLE1
source = TABLE2
source = TABLE3
source = TABLE4
source = TABLE5
...
path = /data/sphinx/all_table_index
#docinfo = extern
charset_type = utf-8
}
Additionally: The unique integer field has duplicates (Primary ID Auto increment - same for each table!). Does that affect any search for any other fields?
Thank you for your help.
> The unique integer field has duplicates (Primary ID Auto increment - same for each table!).
That is your problem.
The document-id MUST be unique. Its how sphinx tracks documents, so if you have multiple documents with the same id, they will override each other, and you then have no way to distingish the seperate underlying documents.
... So you need to arrange for the IDS to be unique.
There are many ways to do it, eg
sourse TABLE1 {
sql_query = SELECT id*20 as id, ... from table1
sourse TABLE2 {
sql_query = SELECT (id*20)+1 as id, ... from table2
sourse TABLE3 {
sql_query = SELECT (id*20)+2 as id, ... from table3
etc...
Usually use this
source TABLE1 {
sql_query = SELECT CONCAT(id,01) as id, 'table1' AS source, '01' AS source_code, ... from table1
sql_attr_string = source
sql_attr_str2ordinal = source_code
01 and not 1, 001 if more than 100 sources (but never happen for me)
'table1' AS source just to easy know the source"
'01' AS source_code just to easy filter, or groupby

How can insert data using the select statement

How can I insert data using the select statement...
I have come across a question asking, what is select * from orders; used for?
And the answer was for viewing and inserting ....
Please provide an explanation ...
The answer "for viewing and inserting" is misleading and incomplete; SELECT returns data, which can then be used in almost any SQL statement.
For most normal use cases, you insert data using an INSERT statement.
INSERT INTO MyTable (MyColumn)
VALUES ('MyValue')
In some cases you may want to insert data that you are pulling from another table (or view), in which case you might use this syntax:
INSERT INTO MyTable (MyColumn)
SELECT MyColumn
FROM MyTableOrMyOtherTableOrView
Note that the exact syntax may vary depending upon your database platform.
To insert values based on a select use this syntax:
insert into table1 (mycol)
select mycol from table2
You can also use select into that enables you to create a new table : select into
And select * from table1 means select every column from table1
For a full tutorial on SQL try W3schools
You use
insert into tableX(columnsX) select columnsY from tableY
to insert data from tableY to tableX. They can both be the same. columnsY is a list of columns that exists in tableY and it must match column types in tableY.
That basically means that you'll be inserting existing data into tableX, and that existing data comes from tableY.
For the question,
"what is "select * from orders ;" used for?"
the answer
for viewing and inserting
is not correct. It is only for viewing, not inserting.
private void cnd()
{
SqlConnection con = new SqlConnection("Data Source = serverName;User ID = serverId;Password = serverPassword;Initial Catalog = DatabaseName");
con.Open();
SqlDataAdapter dp = new SqlDataAdapter("SELECT * FROM tableName", con);
SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(dp);
DataSet ds = new DataSet("tableName");
dp.Fill(ds, "tableName");
DataRow dr = ds.Tables["tableName"].NewRow();
dr["columnName"] = "Value";
dr["columnName"] = "Value";
ds.Tables["tableName"].Rows.Add(dr);
int re = dp.Update(ds, "tableName");
Console.WriteLine(re.ToString());
con.Close();
}