How can insert data using the select statement - sql

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();
}

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).

SQL Select Multiple table at onces

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;

Checking if a table is empty or not

I am making a vb.net project. In one form, I want it to work like if user presses a button it first checks if a table(Built with SQL Server) is empty or not. If it is empty it will open another form otherwise Resume functioning. How to check if the table is empty or not.
Thanks.
If you are after a sql statement that are check if there any rows in a table. THen you can do something like this:
SELECT
(
CASE WHEN NOT EXISTS(SELECT NULL FROM yourTable)
THEN 1
ELSE 0
END
) AS isEmpty
You can execute a SQL query to find the row count of your required table and then based on that count you can apply your logic by using conditional commands like If[...]Else:
Dim count As Int16
con.open()
query = "select count(*) from requiredTable"
cmd = New SqlCommand(query, con)
count = Convert.ToInt16(cmd.ExecuteScalar())
con.Close()
Alternatively
SELECT TOP(1) 1 FROM MyTable
and in your vb code check the number of rows returned ( 0 rows = table is empty)
A Bit late, but for all people googled the same:
Slow Version:
select distinct 1 from MyTable ;
select count(*) from MyTable ;
Fast Version:
select count(*) from (select 1) where exists (select * from MyTable);
Maybe different products may have different results

Using a SubQuery in an Insert Statement in SQL Server 2005

I have a carsale project. It completely works on localhost. I have a "AddCar.aspx" page that inserts a car record with car's features. Car features are selected with checkboxes. If i don't check any checkbox, there is no problem. But if i check one of feature checkboxes, my page gives an error like this:
"Subqueries are not allowed in this
context. Only scalar expressions are
allowed."
And my code is like that:
foreach (DataListItem item in Security1.Items) {
CheckBox CheckBox1 = (CheckBox)item.FindControl("CheckBox1");
if (CheckBox1.Checked) {
HiddenField h = (HiddenField)item.FindControl("FeaID");
string add = "Insert into Carfeature (RecID,FeatureID) values ((select Max(RecID) from record),#FeatureID)";
cmd[k] = new SqlCommand();
cmd[k].CommandType = CommandType.Text;
cmd[k].Parameters.Add("#FeatureID", SqlDbType.Int).Value = h.Value;
cmd[k].CommandText = add;
k++;
}
}
Is there any solution?
Two things, first of all, try this SQL:
Insert into Carfeature (RecID,FeatureID)
select Max(RecID), #FeatureID from record;
Secondly, the Max(RecId) is problematic if you have multiple threads doing this. Are you aware that you can get the last inserted identity? Isn't that what you want to do here? If you've just inserted a record into the record table in the previous step
select SCOPE_IDENTITY() as RecID;
will give you the correct RecID in a thread safe manner.
Change your SQL to this:
Insert into Carfeature (RecID,FeatureID)
select Max(RecID), #FeatureID from record
I think you could just re-format your sql and do it this way:
Insert into Carfeature (RecID,FeatureID) select Max(RecID), #FeatureId from record
This is most likely due to concurrency control. A way I'd recommend doing this on SQL Server 2005 is to change your sql statement to the following using CTE's(http://msdn.microsoft.com/en-us/library/ms190766.aspx):
with MaxId as
(
select Max(RecID)
from record
)
insert into Carfeature (RecID,FeatureID)
select #MaxID, #FeatureID
from MaxId
Friends, you all answered true, thanks a lot.
I changed my code like that and it worked:
Insert into Carfeature (RecID,FeatureID) select Max(RecID), #FeatureID from record
But I don't know how to set accepted answer, because all of answers are true :)

Using SQl Server CE; Possible to Insert Only If Not Exists?

I'm trying to verify a simple 1 field table to determine if a record exists before inserting a duplicate.
if not exists (select * from url where url = ...)
insert into url...
Can someone Help?
Your code example will run in the full version of SQL, or you could rearrange to the following:
insert into url
select 'myvalue'
where not exists (select * from url where url = 'myvalue')
Just reverse it and add the condition as a where clause predicate
Insert Into Table ....
Where Not Exists
(Select * From table where ...)
... But your basic problem sounds like it might be better solved by putting a alternate key (unique) constraint on the insert table, referencing the url column (I assume Sql CE does Referential Integrity (RI) constraints?)
You might want to read this thread. performing-insert-or-update-upsert-on-sql-server-compact-edition
In a nutshell a sqlce specific solution (using SqlCeResultSet) will provide the maximum performance.
Use an Outer Join
Insert into X(...)
select blah, blah, blah
from
table t left outer join
X on t.id=x.id
where
x.id is null
Granted, this is way past the posting date, but since I've not seen this answered elsewhere in my quick Google search, I thought I'd share how I solved this with SQL CE so others searching might find an answer.
-- Update existing record's value
UPDATE myTable SET myValue = 'Hello World' WHERE keyField = 'MyKey';
-- Insert new record if existing record doesn't exist`
INSERT INTO myTable (keyField, myValue)
SELECT I.keyField, I.myValue
FROM (
SELECT 'Hello World' AS myValue, 'MyKey' AS keyField
) I
LEFT JOIN myTable T ON I.keyField = T.keyField
WHERE T.keyField IS NULL;
You are on the right path with IF NOT EXISTS. It is better to use IF NOT EXISTS() or IF EXISTS() than a Sub Query because SQL Server will stop scanning rows in the table when it finds the first instance that matches the EXISTS() condition your looking for. With a Sub Query written in the examples above it will scan the whole table.
A Classic example is the Insert or Update aka the SAVE.
IF EXISTS(SELECT * FROM Table_A WHERE Column_1 = #Parameter)
BEGIN
--Update Statement here.
END
ELSE
BEGIN
--Insert Statement here.
END
What about something like this:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF ##ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
Source