Reputation: 51
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 ...
Upvotes: 0
Views: 3608
Reputation: 171351
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.
Upvotes: 2
Reputation: 1
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();
}
Upvotes: 0
Reputation: 47183
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.
Upvotes: 0
Reputation: 47280
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
Upvotes: 0