Related
I have to convert an int column to a text column and replace the integer values within that column.
For example I have a column status that can contain values like 0, 1, 2, 3, 4, 5, 6, 7.
For '0' I have to replace the value with "New", for '1' with "Identified" and so on.
For this scenario how to write a SQL query?
Personally, I'd go with a mapping table, but another option is CHOOSE() or even the traditional CASE
Note the +1 in the CHOOSE option ... 0 is not a valid option and would return NULL
Example
Declare #YourTable Table ([Status] int)
Insert Into #YourTable Values
(0),(1),(2),(3)
Select *
,ViaCHOOSE = choose([Status]+1,'New','Identified','Some Other','...')
,ViaCASE = case [Status]
when 0 then 'New'
when 1 then 'Identified'
when 2 then 'Some Other'
else null -- or 'Undefined'
end
From #YourTable
Results
Status ViaCHOOSE ViaCASE
0 New New
1 Identified Identified
2 Some Other Some Other
3 ... ...
You could create a (temporary) table with that mapping.
create table XYMapping (number int, text varchar(max));
INSERT INTO XYMapping (number, text) VALUES (1, 'New'), (2, 'Identified'); -- ...
Insert all values and then join them.
Steps to follow to convert int column to text and replace the existing values.
Alter the table. Since INT converts to text implicitly NOT NULL is able to be maintained
Exec UPDATE statement using conversion table specified using VALUES table value constructor
Something like this
drop table if exists #samples;
go
create table #samples (
id int not null,
stat varchar(10) not null);
insert #samples(id, stat) values
(10, 'Start'),
(1, 'Start'),
(1, 'Failed'),
(2, 'Start'),
(3, 'Start'),
(3, 'Failed'),
(4, 'Start'),
(4, 'Failed'),
(4, 'Start'),
(4, 'Failed');
/* step 1: alter the table (and implicitly convert) */
alter table #samples
alter column
id varchar(20) not null;
/* step 2: update based on conversion table */
update s
set id=v.new_str
from #samples s
join
(values ('1', 'New'),
('2', 'Identified'),
('3', 'Identified'),
('4', 'Identified'),
('10', 'Other')) v(old_int, new_str) on s.id=v.old_int;
select * from #samples;
id stat
Other Start
New Start
New Failed
Identified Start
Identified Start
Identified Failed
Identified Start
Identified Failed
Identified Start
Identified Failed
I found this SQL on internet but it is giving me some errors and I don't know how to fix it?
Can I have help with this SQL please?
Create Table Veterinarians
(vetName varchar2(20),
vid Number(5) primary key);
Create Table Dogs
(dogName varchar2(20),
did Number(5) primary key);
Create Table Location
(lid Number(5) primary key,
locName varchar2(20),);
Create Table Examine
(vid int foreign key references Veterinarians(vid),
did int foreign key references Dogs(did),
lid int foreign key references Location(lid),
fee Number(5));
INSERT INTO Veterinarians VALUES ('Alice',112);
INSERT INTO Veterinarians VALUES ('Mary',211);
INSERT INTO Veterinarians VALUES ('Jim',111);
INSERT INTO Dogs VALUES ('Spot',324);
INSERT INTO Dogs VALUES ('Fido',582);
INSERT INTO Dogs VALUES ('Tiger',731);
INSERT INTO Location VALUES (1001,'St.Cloud');
INSERT INTO Location VALUES (1002,'Minneapolis');
INSERT INTO Location VALUES (1003,'Duluth');
INSERT INTO Examine VALUES (111,324,1001,10);
INSERT INTO Examine VALUES (111,731,1003,20);
INSERT INTO Examine VALUES (112,324,1001,30);
INSERT INTO Examine VALUES (112,582,1001,50);
INSERT INTO Examine VALUES (112,731,1002,35);
INSERT INTO Examine VALUES (211,324,1001,25);
INSERT INTO Examine VALUES (211,582,1002,35);
INSERT INTO Examine VALUES (211,731,1001,20);
INSERT INTO Examine VALUES (211,582,1001,25);
INSERT INTO Examine VALUES (211,582,1003,65);
--Creating a stored procedure
Create PROCEDURE display_Avg(vid int) AS
BEGIN
select v.vid,v.vetName,Avg(e.fee) as AverageFee
from Veterinarians v
INNER JOIN Examine e
ON v.vid=e.vid
Where v.vid=display_Avg.vid
Group By v.vid,v.vetName;
END;
--Executing stored procedure
Execute display_Avg(112);
CREATE PROCEDURE display_DogNames
AS BEGIN
select dogName
from Dogs
INNER JOIN Examine
ON Examine.did=Dogs.did
INNER JOIN Location
On Examine.lid=Location.lid
Where Location.lid=1001
AND Location.lid=1002
AND Location.lid=1003
END;
Here are the errors it is giving me
Msg 102, Level 15, State 1, Procedure display_Avg, Line 46 [Batch
Start Line 0] Incorrect syntax near 'vid'.
Msg 102, Level 15, State 1, Procedure display_Avg, Line 57 [Batch
Start Line 0] Incorrect syntax near '112'.
Msg 111, Level 15, State 1, Procedure display_Avg, Line 60 [Batch
Start Line 0] 'CREATE/ALTER PROCEDURE' must be the first statement in
a query batch.
You can use this code:
CREATE TABLE Veterinarians (
vetName varchar(20),
vid int NOT NULL PRIMARY KEY
);
CREATE TABLE Dogs (
dogName varchar(20),
did int NOT NULL PRIMARY KEY
);
CREATE TABLE tblLocation (
lid int NOT NULL PRIMARY KEY,
locName varchar(20)
);
CREATE TABLE Examine (
vid int NOT NULL FOREIGN KEY REFERENCES Veterinarians (vid),
did int NOT NULL FOREIGN KEY REFERENCES Dogs (did),
lid int NOT NULL FOREIGN KEY REFERENCES tblLocation (lid),
fee int
);
INSERT INTO Veterinarians
VALUES ('Alice', 112);
INSERT INTO Veterinarians
VALUES ('Mary', 211);
INSERT INTO Veterinarians
VALUES ('Jim', 111);
INSERT INTO Dogs
VALUES ('Spot', 324);
INSERT INTO Dogs
VALUES ('Fido', 582);
INSERT INTO Dogs
VALUES ('Tiger', 731);
INSERT INTO tblLocation
VALUES (1001, 'St.Cloud');
INSERT INTO tblLocation
VALUES (1002, 'Minneapolis');
INSERT INTO tblLocation
VALUES (1003, 'Duluth');
INSERT INTO Examine
VALUES (111, 324, 1001, 10);
INSERT INTO Examine
VALUES (111, 731, 1003, 20);
INSERT INTO Examine
VALUES (112, 324, 1001, 30);
INSERT INTO Examine
VALUES (112, 582, 1001, 50);
INSERT INTO Examine
VALUES (112, 731, 1002, 35);
INSERT INTO Examine
VALUES (211, 324, 1001, 25);
INSERT INTO Examine
VALUES (211, 582, 1002, 35);
INSERT INTO Examine
VALUES (211, 731, 1001, 20);
INSERT INTO Examine
VALUES (211, 582, 1001, 25);
INSERT INTO Examine
VALUES (211, 582, 1003, 65);
IF OBJECT_ID('dbo.display_Avg') > 0
DROP PROCEDURE dbo.display_Avg
GO
--Creating a stored procedure
CREATE PROCEDURE display_Avg (#vid int)
AS
BEGIN
SELECT
v.vid,
v.vetName,
AVG(e.fee) AS AverageFee
FROM Veterinarians v
INNER JOIN Examine e
ON v.vid = e.vid
WHERE v.vid = #vid
GROUP BY v.vid,
v.vetName;
END;
--Executing stored procedure
EXECUTE display_Avg 112;
IF OBJECT_ID('dbo.display_DogNames') > 0
DROP PROCEDURE dbo.display_DogNames
GO
CREATE PROCEDURE display_DogNames
AS
BEGIN
SELECT
dogName
FROM Dogs
INNER JOIN Examine
ON Examine.did = Dogs.did
INNER JOIN tblLocation
ON Examine.lid = tblLocation.lid
WHERE tblLocation.lid = 1001
AND tblLocation.lid = 1002
AND tblLocation.lid = 1003
END;
EXEC display_DogNames
The modifications are:
1.-Type is VARCHAR not varchar2
2.-For the primary key its INTEGER and not need the long like "int (5)"
3.-Add not null in primary keys for not accept nulls
4.-Changue the name of Location to tblLocation in case "Location" be a reserv word by SQL
5.-Destroy the object before creat:
IF OBJECT_ID ('dbo.display_DogNames')> 0
DROP PROCEDURE dbo.display_DogNames
GO
6.-The params in the procedure have an # before the name of the param: #vid
7.-Finally to excecute an procedure you don't need the "()" symbols: EXECUTE display_Avg 112;
If you want to drop the tables, remember doing in orden keeping in mind the foreign key:
1- drop table Examine
2- drop table tblLocation
3- drop table Veterinarians
4- drop table Dogs
Why start with a script that you cannot run and cannot debug. Find a sample database that is well-defined and use it for learning to write tsql queries. That approach will also avoid the problems with attempting to design a database without a proper foundation of relational knowledge. MS has published the sample databases here.
But that probably won't deter you, so the solution is to break your script into batches. Quite simply add a line containing "GO" before every "create procedure" statement as well as one immediately after the creation of the first procedure since it is followed by an execute statement for that same procedure.
GO -- **HERE**
--Creating a stored procedure
Create PROCEDURE display_Avg(vid int) AS
BEGIN
select v.vid,v.vetName,Avg(e.fee) as AverageFee
from Veterinarians v
INNER JOIN Examine e
ON v.vid=e.vid
Where v.vid=display_Avg.vid
Group By v.vid,v.vetName;
END;
GO -- **HERE**
--Executing stored procedure
Execute display_Avg(112);
GO -- **HERE**
CREATE PROCEDURE display_DogNames
AS BEGIN
select dogName
from Dogs
INNER JOIN Examine
ON Examine.did=Dogs.did
INNER JOIN Location
On Examine.lid=Location.lid
Where Location.lid=1001
AND Location.lid=1002
AND Location.lid=1003
END;
I am having a table like this along with data
CREATE TABLE temp (
`name` varchar(20),
`ids` varchar(20),
`value1` int,
`value2` int
);
INSERT INTO temp(`name`,`ids`, `value1`, `value2`) values
('A', '1,2', 10, 11),
('A', '2,1', 12, 100),
('A', '1,2,3', 20, 1),
('B', '6', 30, 10)
I need to get the max value by Name along with ids
I am using the following query to get the max value.
select name, ids, max(value1) as value1, max(value2) as value2
from temp
group by name,ids
The question has been tagged as Sybase ASE, but the 'create table and 'insert' commands are invalid in ASE so not sure if this is an issue of an incorrect tag or the wrong 'create table' and 'insert' commands ... so, assuming this is for a Sybase ASE database:
I'm assuming the desired output is to display those rows where value = max(value).
First we'll setup our test case:
create table mytab
(name varchar(20)
,ids varchar(20)
,value int)
go
insert into mytab (name,ids,value) values ('A', '1,2' , 10)
insert into mytab (name,ids,value) values ('A', '2,1' , 12)
insert into mytab (name,ids,value) values ('A', '1,2,3', 20)
insert into mytab (name,ids,value) values ('B', '6' , 30)
go
Here's one possible solution:
select t.name, t.ids, t.value
from mytab t
join (select name,max(value) as maxvalue from mytab group by name) dt
on t.name = dt.name
and t.value = dt.maxvalue
order by t.name
go
name ids value
-------------------- -------------------- -----------
A 1,2,3 20
B 6 30
The subquery/derived-table gives us the max(value) for each unique name. The main query then joins these name/max(value) pairs back to the main table to give us the desired rows (ie, where value = max(value)).
Tested on ASE 15.7 SP138.
Hi guys I just have one quick question:
what happens when an insert statement fails on an identity column?
Is it possible that say for example that if I insert a row with an identity column, that identity column will be 1, and insert again but that fails and does not insert and data. Then try to insert again and that identity for that row is now 3?
Any advice will be much appreciated.
Thanks.
It depends on what the cause of the fail on data insert is. If for example the values are invalid (wrong types), then the identity value won't be incremented. However, if the first insert is successful, but is then removed (by a transaction failed and rolled back), then the identity value IS incremented.
-- Next identity value = 1
INSERT INTO Table1 (
field1)
VALUES ('a')
-- Next identity value = 2
BEGIN TRAN
INSERT INTO Table1 (
field1)
VALUES ('b')
-- Next identity value = 3
ROLLBACK TRAN
-- Next identity value = 3, although the insertion was removed.
INSERT INTO Table1 (
field1)
VALUES ('c')
-- Next identity value = 4
The first insert will have identity column value = 1, the second one fails, and the third one will have identity column value = 3.
Just because a column has an IDENTITY specification doesn't necessarily mean it's unique.
If you don't have a unique constraint (or a primary key constraint) on that column, you can definitely insert multiple identical values into rows for that column.
Typically, though, your IDENTITY columns will be the primary key (or at least have a UNIQUE constraint on them) and in that case, attempting to insert a value that already exists will result in an error ("unique constraint violation" or something like that)
In order to be able to insert specific values into an IDENTITY column you need to have the SET IDENTITY_INSERT (table name) ON - otherwise, SQL Server will prevent you from even specifying values for an IDENTITY column.
For illustration - try this:
-- create demo table, fill with values
CREATE TABLE IdentityTest (ID INT IDENTITY, SomeValue CHAR(1))
INSERT INTO IdentityTest(SomeValue) VALUES('A'), ('B'), ('C')
SELECT * FROM IdentityTest -- Output (1)
-- insert duplicate explicit values into table
SET IDENTITY_INSERT IdentityTest ON
INSERT INTO IdentityTest(ID, SomeValue) VALUES(1, 'Z'), (2, 'Y')
SET IDENTITY_INSERT IdentityTest OFF
SELECT * FROM IdentityTest -- Output (2)
-- add unique constraint
TRUNCATE TABLE dbo.IdentityTest
ALTER TABLE IdentityTest ADD CONSTRAINT UX_ID UNIQUE(ID)
INSERT INTO IdentityTest(SomeValue) VALUES('A'), ('B'), ('C')
SET IDENTITY_INSERT IdentityTest ON
INSERT INTO IdentityTest(ID, SomeValue) VALUES(1, 'Z') -- error message (3)
DROP TABLE IdentityTest
Output (1):
ID SomeValue
1 A
2 B
3 C
Output (2):
ID SomeValue
1 A
2 B
3 C
1 Z
2 Y
Error Message (3):
Msg 2627, Level 14, State 1, Line 9
Violation of UNIQUE KEY constraint 'UX_ID'. Cannot insert duplicate key in object 'dbo.IdentityTest'. The duplicate key value is (1).
One way is to prevent the insert if the row already exists.
IF (Not Exists (Select ID From Table Where SomeCol = #SomeVal)
Insert Into Table Values (#SomeVal)
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;