How can I make this an insert statement - sql

I am new to SQL, So I have a table called 'DealerShip' and I have a many different car ID's . I have a dealership called 'Hondo' and another one called 'Mitch' . I would like to insert about 80 records into 'Mitch' that 'Hondo' has . For instance with this Query
select * from DealerShips where name='Hondo' and CarType=63
That query above contains about 70 records, How can I create an insert statement that will insert all the returned records from that query above ? The insert will go into the same table above except that the name will be 'Mitch' . I am using MSSQL 2012

INSERT INTO SELECT
INSERT INTO yourtable (FIELDS...) ---- fields here should match the select fields
SELECT FIELDS... FROM
DealerShips where name = 'Hondo' and CarType=63

Just make sure you list the columns in the insert and the select in the same order.
INSERT INTO DealerShips (name, cartype, more columns)
SELECT
'Mitch'
, cartype
, more columns
from DealerShips where name='Hondo' and CarType=63

Related

Foreach insert statement based on where clause

I have a scenario where I have thousands of Ids (1-1000), I need to insert each of these Ids once into a table with another record.
For example, UserCars - has columns CarId and UserId
I want to INSERT each user in my Id WHERE clause against CarId 1.
INSERT INTO [dbo].[UserCars]
([CarId]
,[UserId])
VALUES
(
1,
**My list of Ids**
)
I'm just not sure of the syntax for running this kind of insert or if it is at all possible.
As you write in the comments that my list of Ids is coming from another table, you can simply use select into with a select clause
See this for more information
insert into UserCars (CarID, UserID)
select CarID, UserID
from othertable
In the select part you can use joins and whatever you need, complex queries are allowed as long as the columns in the result match the columns (CarID, UserID)
or even this to keep up with your example
insert into UserCars (CarID, UserID)
select 1, UserID
from dbo.User
if your data exists on a file, you can use BULK INSERT command, for example:
BULK INSERT UserCars
FROM '\\path\to\your\folder\users-cars.csv';
Just make sure to have the same columns structure both in the file and in the table (e.g. CarId,UserId).
Otherwise, follow #GuidoG comment to insert your data from another table:
insert into UserCars (CarID, UserID) select CarID, UserID from othertable

Inserting data into a table(mutliple columns) which has primary key from another data which has data except primary key

I have a table that has 3 columns ID(Primary Key), Name, City.
I need to import data from another table that has only Name and City.
I can write insert into table 1(Name, City) select Name, City from table2.
But then I need ID in table 1 which needs to be inserted using a sequence.
I tried this:
insert into table1(ID, Name,City) values(seq.nextval, select distinct name, city from table2). But I am receiving an error saying an insufficient number of values.
I am trying it in SQL Oracle. Can someone please help me with this?
You are mixing the insert ... values and insert ... select syntax.
You edited your question to include distinct, implying you have duplicate name/city pairs that you want to suppress; but neither version gets the error you reported. If you don't have duplicates then you can just do:
insert into table1(ID, Name,City)
select seq.nextval, name, city from table2;
If you do have duplicates then you can't just add the distinct keyword, but you can use a subquery:
insert into table1 (id, name, city)
select seq.nextval, name, city
from (
select distinct name, city
from table2
);
db<>fiddle
You could also set the ID via a trigger. If you we're on a recent version you could use an identity column instead - but you tagged the question with Oracle 11g, where those are not available.

SQL Server How to insert multiple values while excluding repeating values

I'm developing a query for a program where user has to enter one or multiple multiple values into a DB table.
The issue with the query is when you try to insert multiples values it could be that some of those values are repeated in the tables and the warning will only display one repeated value at a time and that might be a problem when you are working with a 1000+ values.
Error Message:
Cannot insert duplicate key row in object 'ItemWebCategory' with unique index 'IX_StyleID_WebCategoryID'. The duplicate key value is (1109068, 99999).
Query
insert into ItemWebCategory (Style_id,WebCategoryID)
select distinct Style_id,WebCategoryID = '99999'
from ItemCategory
where style_id in ('1109068','168175', '68435', '545457', '69189')
Question
How can I modify the query so it may skip/exclude all repeating values and only insert the values that do no exist on the table?
Try something like this:
INSERT INTO ItemWebCategory ( Style_id, WebCategoryID )
SELECT DISTINCT
Style_id,
'99999' AS WebCategoryID
FROM ItemCategory WHERE Style_id NOT IN (
SELECT Style_id FROM ItemWebCategory
);
The NOT IN excludes any Style_id values that already exist in ItemWebCategory.
You have two straight-forward options:
NOT EXISTS
insert into ItemWebCategory (Style_id,WebCategoryID)
select distinct Style_id,WebCategoryID = '99999'
from ItemCategory ic
where style_id in ('1109068','168175', '68435', '545457', '69189')
AND NOT EXISTS (SELECT 1
FROM ItemWebCategory iwc
WHERE ic.Style_id = iwc.Style_id
);
EXCEPT
insert into ItemWebCategory (Style_id,WebCategoryID)
select Style_id,WebCategoryID = '99999'
from ItemCategory
where style_id in ('1109068','168175', '68435', '545457', '69189')
EXCEPT
SELECT Style_id
FROM ItemWebCategory;
Now there's no need for DISTINCT because EXCEPT implies DISTINCT
One more useful option is a MERGE. This has performance benefits due to Halloween Protection (an entire subject in itself) as explained by Paul White:
MERGE ItemWebCategory AS target
USING (
select Style_id, WebCategoryID = '99999'
from ItemCategory
where style_id in ('1109068','168175', '68435', '545457', '69189')
) AS source
ON target.Style_id = source.Style_id
WHEN NOT MATCHED THEN INSERT
(Style_id, WebCategoryID)
VALUES (source.Style_id, source.WebCategoryID);

Need help to get an insert statement in SQL Server

I would need to insert the non existing values to a Table.
Table name BarcodeSubgroup (single column table)
Column (nvarchar)
Sample data in the table
ProductSubGroupID
-----------------
F11WD
F77AH
G36CN
G37HJ
H11AA
H11AD
Now I need to insert the non existing values in the table.
Values want to be checked and inserted.
H11AA
H11AD
G78DE
G76DK
G41JA
B45JC
Query written
insert into BarcodeSubgroup
select
productsubgroupid
where
not exists ('G78DE', 'G76DK', 'G41JA',
'B45JC', 'H11AA', 'H11AD')
Now it should insert only the 4 non existing values.
You can do this with select . . . not exists:
insert into BarcodeSubgroup(productsubgroupid)
select productsubgroupid
from (values ('G78DE'), ('G76DK'), ('G41JA'), ('B45JC'), ('H11AA'), ('H11AD') ) v(productsubgroupid)
where not exists (select 1
from BarcodeSubgroup bs
where bs.productsubgroupid = v.productsubgroupid
);

SQL 'simple' query syntax error - help!

My query returns a syntax error:
Invalid object name 'table.clientinfo'.
Here is my query:
INSERT table.clientinfo (name, addr, entry, affiliate )
SELECT name, addr, entry, affiliate FROM table.clientinfo WHERE product = 5
Is the error due to the insert function not finding 'clientinfo' as it does not exist.
Can anybody give me the correct syntax to create the table first before populating it from the select function?
You want CREATE TABLE
CREATE TABLE clientinfo (
name VARCHAR(100)
addr VARCHAR(100)
entry VARCHAR(100)
affiliate VARCHAR(100)
);
with specific types/sizes for your app. You might want to indicate foriegn and primary keys, constraints etc too
In SQL Server, if you want to select and insert into a new table, use this syntax:
SELECT name, addr, entry, affiliate
INTO (new table name)
FROM [table.clientinfo]
WHERE product = 5
You need to SELECT .... INTO and you need to make sure to use proper table names.
If you table name really has a dot in it (really really bad practice!), then you MUST put that table name in square brackets: FROM [table.clientinfo]
Also, when doing SELECT .. INTO ... you cannot select from an existing table and insert into the same existing table - you need to use a new table name for your destination table.
You should use
INSERT INTO [tablename] (field1, field2, ... , fieldx)
SELECT ...
Or if you want to create the other data directly:
SELECT field1, field2, ... , fieldx
INTO newTable
FROM oldtable
WHERE ....