Insert into with select statement where value is not null - sql-server

I want to perform an insert operation based on the select statement from another table in SQL Server.
I have built this:
INSERT INTO Table1
SELECT table2.var1, table2.var2, 1, GETDATE(), 1, GETDATE(),0
FROM table2
The values in Table1 are all NOT NULL, and there is a couple of record of table2.var2 where there is a null value, I want to skip the Null and continue with the operation.

You can filter the rows where table2.var2 is null in a WHERE clause.
INSERT INTO table1
(<list of target columns>)
SELECT table2.var1,
table2.var2,
1,
getdate(),
1,
getdate(),
0
FROM table2
WHERE table2.var2 IS NOT NULL;
You should also explicitly list the targeted columns in any INSERT so that statements don't break if the number or order of columns change in the target table.

Related

Inserting rows from one database table into two different tables in another database

I need to add about 600 records from one database to another one.
The first part inserts from a select like this:
INSERT INTO RelayMapper.dbo.radioSignals(CstarID, StarName, SystemName, StarSystemCount, SuperNova, DateCreated)
SELECT NEWID(), startName, systemName, 1, 1, getDate()
FROM AISourceMapper.dbo.radioSignals
WHERE rangeICW = 5
This is where it gets tricky and I don't know how to do it.
So for each row inserted above, I need to also insert related data into another table.
The NEWID() above would be used to insert a row and then I'd need to insert the starCoordinates as well from AISourceMapper.dbo.radioSignals and it would look something like this:
INSERT INTO RelayMapper.dbo.radioSources(CstarID, starCoordinates, isVerified)
VALUES('1150C651-5D9A-4C13-9BE7-EF4AZ2549112', 'R.A. 13h 27m, DEC. -47deg, 29m', 1)
starCoordinates is also from the same table and row that I'm SELECTing from(AISourceMapper.dbo.radioSignals)
Is there a way to do something like this?
One option is to copy all data from AISourceMapper.dbo.radioSignals into a temp table and at the same time assign GUIDS and then insert from this table into your destination tables.
SELECT NEWID() AS CstarID, *
INTO #TempTable
FROM AISourceMapper.dbo.radioSignals
WHERE rangeICW = 5
INSERT INTO RelayMapper.dbo.radioSignals( CstarID, StarName, SystemName, StarSystemCount, SuperNova, DateCreated )
SELECT CstarID, startName, systemName, 1, 1, getDate()
FROM #TempTable
INSERT INTO RelayMapper.dbo.radioSources( CstarID, starCoordinates, isVerified )
SELECT CstarID, starCoordinates, isVerified
FROM #TempTable
You can use OUTPUT clause to get the inserted values and then use them to insert into another table.
DECLARE #insertedId TABLE(CStartID UNIQUEIDENTIFIER)
INSERT INTO RelayMapper.dbo.radioSignals(CstarID, StarName, SystemName, StarSystemCount, SuperNova, DateCreated)
OUTPUT inserted.CStarID INTO #insertedId
SELECT NEWID(), startName, systemName, 1, 1, getDate()
FROM AISourceMapper.dbo.radioSignals
WHERE rangeICW = 5;
--with values clause
INSERT INTO RelayMapper.dbo.radioSources(CstarID, starCoordinates, isVerified)
SELECT CStarId
'R.A. 13h 27m, DEC. -47deg, 29m', 1
FROM #insertedId;
--WITH select clause
INSERT INTO RelayMapper.dbo.radioSources(CstarID, starCoordinates, isVerified)
SELECT i.CStarId, rs.starCoordinates, 1
FROM AISourceMapper.dbo.radioSignals AS rs
CROSS JOIN #insertedId AS i
WHERE rs.rangeICW = 5;

Insert multiple column with where clause

While inserting multiple columns of data with where condition, I get an error
insert into s_grpeffect(grpeffect_cess, grpeffect_rcm, grpeffect_fulllife)
values ('12.0000', '12.0000', '2019')
where grpeffect_grpkid = 124;
You cannot add where clause for insert statement.
insert into s_grpeffect(grpeffect_cess,grpeffect_rcm,grpeffect_fulllife) values('12.0000','12.0000','2019')
Or If you are selecting value from table then below is the syntax,
INSERT INTO table2
SELECT * FROM table1
WHERE condition;

Insert trigger for a spesific column

I have two tables. When I insert a new value for a spesific column I want to update another column in the second table. How I can do that?
Here is a simple example but it gives "Incorrect syntax near the keyword 'Insert'." error as expected.
Create trigger trigger_Insert_Months
on [Quantities]
after Insert
As
if Insert([Work Name])
begin
declare #NewWorkName varchar(200)
select #NewWorkName = [Work Name] from inserted
insert into [April]([Work Name])
values (#NewWorkName)
End
Try This:
CREATE TRIGGER trigger_Insert_Months
ON [Quantities]
AFTER INSERT
AS
BEGIN
INSERT INTO [April]([Work Name])
SELECT [Work Name] from inserted
WHERE NOT EXISTS (SELECT 1 FROM [Quantities] WHERE [Quantities].[Work Name] = INSERTED.[Work Name] AND INSERTED.PrimaryKey != [Quantities].[PrimaryKey])
End
Correct me if I am wrong. You want to insert values in table1 and update values in table2 with the inserted values.
create trigger tr1 on Table1
for insert
as
begin
if exists (select 1 from inserted)
begin
update a
set a.col1 = b.col
from table2 as a
inner join (select * from inserted) as b
on a.id = b.id
end
end
This code activates the trigger when an insert happens in Table1 and updates Values of table2 of col1 with the inserted rows.
Change the ID column with the column having primary key in table2 and table1 and col1 with the column to be updated in table2

Insert next records

I have requirement like, I have to insert the records whenever for one BID, one SID, if the execdate and stopbilldate exist, then I need to insert new record with NULL as Stopbilldate
sample example is as follows:
Sno BID SID LID Comapny Execdate StopBilldate
5 BLDG100 C 6500 Cole 1/5/2012 5/29/2012
6 BLDG100 C 000000 Vacant 5/30/2012 NULL
You can do this with a TRIGGER on your table. A trigger is a kind of stored procedure that will execute when an event occurs.
Here is a sample of what you could place on your table:
CREATE TRIGGER [trg_yourTable]
ON [yourTable]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
INSERT INTO yourTable (bid, sid, lid, company, execdate, stopbilldate)
SELECT i.bid, i.sid, 0, 'Vacant', DATEADD(day, 1, i.stopbilldate), null
FROM inserted i
WHERE i.bid is not null
and i.sid is not null
END
When you INSERT data in the table, this will run and INSERT the additional row that you want added to the table.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

I know I've done this before years ago, but I can't remember the syntax, and I can't find it anywhere due to pulling up tons of help docs and articles about "bulk imports".
Here's what I want to do, but the syntax is not exactly right... please, someone who has done this before, help me out :)
INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally')
I know that this is close to the right syntax. I might need the word "BULK" in there, or something, I can't remember. Any idea?
I need this for a SQL Server 2005 database. I've tried this code, to no avail:
DECLARE #blah TABLE
(
ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(100) NOT NULL
)
INSERT INTO #blah (ID, Name)
VALUES (123, 'Timmy')
VALUES (124, 'Jonny')
VALUES (125, 'Sally')
SELECT * FROM #blah
I'm getting Incorrect syntax near the keyword 'VALUES'.
Your syntax almost works in SQL Server 2008 (but not in SQL Server 20051):
CREATE TABLE MyTable (id int, name char(10));
INSERT INTO MyTable (id, name) VALUES (1, 'Bob'), (2, 'Peter'), (3, 'Joe');
SELECT * FROM MyTable;
id | name
---+---------
1 | Bob
2 | Peter
3 | Joe
1 When the question was answered, it was not made evident that the question was referring to SQL Server 2005. I am leaving this answer here, since I believe it is still relevant.
INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'
For SQL Server 2008, can do it in one VALUES clause exactly as per the statement in your question (you just need to add a comma to separate each values statement)...
If your data is already in your database you can do:
INSERT INTO MyTable(ID, Name)
SELECT ID, NAME FROM OtherTable
If you need to hard code the data then SQL 2008 and later versions let you do the following...
INSERT INTO MyTable (Name, ID)
VALUES ('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)
Using INSERT INTO ... VALUES syntax like in Daniel Vassallo's answer
there is one annoying limitation:
From MSDN
The maximum number of rows that can be constructed by inserting rows directly in the VALUES list is 1000
The easiest way to omit this limitation is to use derived table like:
INSERT INTO dbo.Mytable(ID, Name)
SELECT ID, Name
FROM (
VALUES (1, 'a'),
(2, 'b'),
--...
-- more than 1000 rows
)sub (ID, Name);
LiveDemo
This will work starting from SQL Server 2008+
This will achieve what you're asking about:
INSERT INTO table1 (ID, Name)
VALUES (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally');
For future developers, you can also insert from another table:
INSERT INTO table1 (ID, Name)
SELECT
ID,
Name
FROM table2
Or even from multiple tables:
INSERT INTO table1 (column2, column3)
SELECT
t2.column,
t3.column
FROM table2 t2
INNER JOIN table3 t3
ON t2.ID = t3.ID
You could do this (ugly but it works):
INSERT INTO dbo.MyTable (ID, Name)
select * from
(
select 123, 'Timmy'
union all
select 124, 'Jonny'
union all
select 125, 'Sally'
...
) x
You can use a union:
INSERT INTO dbo.MyTable (ID, Name)
SELECT ID, Name FROM (
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'
) AS X (ID, Name)
This looks OK for SQL Server 2008. For SS2005 & earlier, you need to repeat the VALUES statement.
INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy')
VALUES (124, 'Jonny')
VALUES (125, 'Sally')
EDIT:: My bad. You have to repeat the 'INSERT INTO' for each row in SS2005.
INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy')
INSERT INTO dbo.MyTable (ID, Name)
VALUES (124, 'Jonny')
INSERT INTO dbo.MyTable (ID, Name)
VALUES (125, 'Sally')
It would be easier to use XML in SQL Server to insert multiple rows otherwise it becomes very tedious.
View full article with code explanations here http://www.cyberminds.co.uk/blog/articles/how-to-insert-multiple-rows-in-sql-server.aspx
Copy the following code into sql server to view a sample.
declare #test nvarchar(max)
set #test = '<topic><dialog id="1" answerId="41">
<comment>comment 1</comment>
</dialog>
<dialog id="2" answerId="42" >
<comment>comment 2</comment>
</dialog>
<dialog id="3" answerId="43" >
<comment>comment 3</comment>
</dialog>
</topic>'
declare #testxml xml
set #testxml = cast(#test as xml)
declare #answerTemp Table(dialogid int, answerid int, comment varchar(1000))
insert #answerTemp
SELECT ParamValues.ID.value('#id','int') ,
ParamValues.ID.value('#answerId','int') ,
ParamValues.ID.value('(comment)[1]','VARCHAR(1000)')
FROM #testxml.nodes('topic/dialog') as ParamValues(ID)
USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
OR YOU CAN USE ANOTHER WAY
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES
('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)
I've been using the following:
INSERT INTO [TableName] (ID, Name)
values (NEWID(), NEWID())
GO 10
It will add ten rows with unique GUIDs for ID and Name.
Note: do not end the last line (GO 10) with ';' because it will throw error: A fatal scripting error occurred. Incorrect syntax was encountered while parsing GO.
Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah and have to specify it every time or use another syntax/approach,
In PostgreSQL, you can do it as follows;
A generic example for a 2 column table;
INSERT INTO <table_name_here>
(<column_1>, <column_2>)
VALUES
(<column_1_value>, <column_2_value>),
(<column_1_value>, <column_2_value>),
(<column_1_value>, <column_2_value>),
...
(<column_1_value>, <column_2_value>);
See the real world example here;
A - Create the table
CREATE TABLE Worker
(
id serial primary key,
code varchar(256) null,
message text null
);
B - Insert bulk values
INSERT INTO Worker
(code, message)
VALUES
('a1', 'this is the first message'),
('a2', 'this is the second message'),
('a3', 'this is the third message'),
('a4', 'this is the fourth message'),
('a5', 'this is the fifth message'),
('a6', 'this is the sixth message');
This is working very fast,and efficient in SQL.
Suppose you have Table Sample with 4 column a,b,c,d where a,b,d are int and c column is Varchar(50).
CREATE TABLE [dbo].[Sample](
[a] [int] NULL,
[b] [int] NULL,
[c] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[D] [int] NULL
)
So you cant inset multiple records in this table using following query without repeating insert statement,
DECLARE #LIST VARCHAR(MAX)
SET #LIST='SELECT 1, 1, ''Charan Ghate'',11
SELECT 2,2, ''Mahesh More'',12
SELECT 3,3,''Mahesh Nikam'',13
SELECT 4,4, ''Jay Kadam'',14'
INSERT SAMPLE (a, b, c,d) EXEC(#LIST)
Also With C# using SqlBulkCopy bulkcopy = new SqlBulkCopy(con)
You can insert 10 rows at a time
DataTable dt = new DataTable();
dt.Columns.Add("a");
dt.Columns.Add("b");
dt.Columns.Add("c");
dt.Columns.Add("d");
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr["a"] = 1;
dr["b"] = 2;
dr["c"] = "Charan";
dr["d"] = 4;
dt.Rows.Add(dr);
}
SqlConnection con = new SqlConnection("Connection String");
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(con))
{
con.Open();
bulkcopy.DestinationTableName = "Sample";
bulkcopy.WriteToServer(dt);
con.Close();
}
Others here have suggested a couple multi-record syntaxes. Expounding upon that, I suggest you insert into a temp table first, and insert your main table from there.
The reason for this is loading the data from a query can take longer, and you may end up locking the table or pages longer than is necessary, which slows down other queries running against that table.
-- Make a temp table with the needed columns
select top 0 *
into #temp
from MyTable (nolock)
-- load data into it at your leisure (nobody else is waiting for this table or these pages)
insert #temp (ID, Name)
values (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally')
-- Now that all the data is in SQL, copy it over to the real table. This runs much faster in most cases.
insert MyTable (ID, Name)
select ID, Name
from #temp
-- cleanup
drop table #temp
Also, your IDs should probably be identity(1,1) and you probably shouldn't be inserting them, in the vast majority of circumstances. Let SQL decide that stuff for you.
Oracle SQL Server Insert Multiple Rows
In a multitable insert, you insert computed rows derived from the rows returned from the evaluation of a subquery into one or more tables.
Unconditional INSERT ALL:- To add multiple rows to a table at once, you use the following form of the INSERT statement:
INSERT ALL
INTO table_name (column_list) VALUES (value_list_1)
INTO table_name (column_list) VALUES (value_list_2)
INTO table_name (column_list) VALUES (value_list_3)
...
INTO table_name (column_list) VALUES (value_list_n)
SELECT 1 FROM DUAL; -- SubQuery
Specify ALL followed by multiple insert_into_clauses to perform an unconditional multitable insert. Oracle Database executes each insert_into_clause once for each row returned by the subquery.
MySQL Server Insert Multiple Rows
INSERT INTO table_name (column_list)
VALUES
(value_list_1),
(value_list_2),
...
(value_list_n);
Single Row insert Query
INSERT INTO table_name (col1,col2) VALUES(val1,val2);
Created a table to insert multiple records at the same.
CREATE TABLE TEST
(
id numeric(10,0),
name varchar(40)
)
After that created a stored procedure to insert multiple records.
CREATE PROCEDURE AddMultiple
(
#category varchar(2500)
)
as
BEGIN
declare #categoryXML xml;
set #categoryXML = cast(#category as xml);
INSERT INTO TEST(id, name)
SELECT
x.v.value('#user','VARCHAR(50)'),
x.v.value('.','VARCHAR(50)')
FROM #categoryXML.nodes('/categories/category') x(v)
END
GO
Executed the procedure
EXEC AddMultiple #category = '<categories>
<category user="13284">1</category>
<category user="132">2</category>
</categories>';
Then checked by query the table.
select * from TEST;

Resources