Generate INSERT statements from a SQL Server Table - sql

I have a table of 3.3 million records and don't want to copy the entire thing from dev to prod (on a client controlled machine and can't get the linked server working correctly).
I only want to copy 300 or so of these records. How do I generate the 300 insert statements?
My select SQL that I want the inserts for is:
select * from data where ID > 9000;
I want a query that will print out all the INSERTS so that I can copy and run it on the production box.

I see you tagged your post SQL-Server-2005, that's too bad because version 2008 has a wizard tool for that.
You could build the insert statements out of concatenated strings.
If field1 is a string, field2 a numeric:
select 'insert into data (field1, field2) values('' || field1 || '', ' || char(field2) ||');' from data where ID < 9000;
Obviously that can be time-consuming if you have lots columns, considering that the strings needs quotes. You may have to convert the numeric columns using char() too.
That should give you a list of insert statements, like this:
insert into data (field1, field2) values('A', 10);
insert into data (field1, field2) values('B', 20);
insert into data (field1, field2) values('C', 30);
Maybe that's not the most elegant way to do this, but it works.

Related

SQL Server : newline character

I have a programming language that does not allow me to write queries on multiple lines. It has to be written all in a single line.
I am unable to send a GO command because it has to be in a new line..
So for example, this does not work:
insert into mytable (field1, filed2) values (1, 2), (3, 4); go
as it should be
insert into mytable (field1, filed2) values (1, 2), (3, 4);
go
I've tried multiple things but none worked:
insert into mytable (field1, filed2) values (1,2),(3,4); \r go
insert into mytable (field1, filed2) values (1,2),(3,4); \r\n go
insert into mytable (field1, filed2) values (1,2),(3,4); $r$n go
insert into mytable (field1, filed2) values (1,2),(3,4); char(10) go
insert into mytable (field1, filed2) values (1,2),(3,4); char(13) go
Is there a way to write it inline, and have SQL Server use it as 2 different lines?
GO is not part of the TSQL language. It is used and recognized only by SSMS and sqlcmd to cut your script into parts ("batches"), and then each part is compiled and run separately, one after the other.
The reason that SSMS and sqlcmd work this way this is that it makes it possible to have e.g. a CREATE TABLE statement, followed by INSERT statements for that table. The INSERT-part will only compile if the table already exists, and that will be the case only after the CREATE has been run.
It is OK to combine multiple INSERTs into one statement. When in doubt about where the next statement should start, you can add a semicolon (;) to mark the end of the previous statement.

Unable to insert this string into a column. Only part of the string Is inserted

I am using SQL Server 2008. And I am trying to insert a string into a table but only part of the string is inserted. I have checked whether it is a SQL injection risk. How to solve or avoid this problem?
insert into tble (col1, col2, col3)
values (23, 34, "out of 8 works, 5 works are completed");
Only Out of 8 Works is inserted, , 5 works are completed was skipped
The double quotes will only work if QUOTED_IDENTIFIERS is turned off, if you are worried about SQL injection then don't pass a string on the INSERT - parameterise it from the application. The string could be truncated because the col3 is not defined long enough - check that also.
Try this..
insert into table(col1,col2,col3) values (23,34,'out of 8 works, 5 works are completed');
Change the size of col3 in your table (based on your string size).
You can change it by using the following query:
alter table tble
alter column col3 nvarchar(100) [null | not null]

Insert rows based on insert statement (nested insert)

A common insert statement is this..
INSERT INTO tbl_name (ID) VALUES (1)
What I wanted to achieve is to Insert an ID using another insert statement from another table.. It would look like this
INSERT INTO tbl_name VALUES (INSERT INTO tbl_name2 (ID) VALUES (1))
I have tried it but it's giving me errors..
INSERT INTO tblReport_OPA (ID_Main) VALUES (INSERT INTO tblReport_OPF (ID_Main) VALUES (1))
I'm currently developing under vb.net 2010 and sql express 2005
You probably can use OUTPUT clause, like this:
INSERT INTO tblReport_OPF (ID_Main)
OUTPUT Inserted.Id_Main
INTO tblReport_OPA
SELECT 1 as Id_Main
Note you'll have to use SELECT instead of VALUES
Opyionally a merge can be used.
merge into #a T1
using (select -1 as ID)Q on Q.ID=T1.ID
WHEN NOT matched by target then
insert(id) values(1)
output
inserted.id
INTO #b;

How to do an insert with multiple rows in Informix SQL?

I want to insert multiple rows with a single insert statement.
The following code inserts one row, and works fine:
create temp table mytmptable
(external_id char(10),
int_id integer,
cost_amount decimal(10,2)
) with no log;
insert into mytmptable values
('7662', 232, 297.26);
select * from mytmptable;
I've tried changing the insert to this, but it gives a syntax error:
insert into mytmptable values
('7662', 232, 297.26),
('7662', 232, 297.26);
Is there a way to get it working, or do I need to run many inserts instead?
You could always do something like this:
insert into mytmptable
select *
from (
select '7662', 232, 297.26 from table(set{1})
union all
select '7662', 232, 297.26 from table(set{1})
)
Pretty sure that's standard SQL and would work on Informix (the derived table is necessary for Informix to accept UNION ALL in INSERT .. SELECT statements).
As you found, you can't use multiple lists of values in a single INSERT statement with Informix.
The simplest solution is to use multiple INSERT statements each with a single list of values.
If you're using an API such as ESQL/C and you are concerned about performance, then you can create an INSERT cursor and use that repeatedly. This saves up the inserts until a buffer is full, or you flush or close the cursor:
$ PREPARE p FROM "INSERT INTO mytmptable VALUES(?, ?, ?)";
$ DECLARE c CURSOR FOR p;
$ OPEN c;
while (...there's more data to process...)
{
$PUT c USING :v1, :v2, :v3;
}
$ CLOSE c;
The variables v1, v2, v3 are host variables to hold the string and numbers to be inserted.
(You can optionally use $ FLUSH c; in the loop if you wish.) Because this buffers the values, it is pretty efficient. Of course, you could also simply use $ EXECUTE p USING :v1, :v2, :v3; in the loop; that foregoes the per-row preparation of the statement, too.
If you don't mind writing verbose SQL, you can use the UNION technique suggested by Matt Hamilton, but you will need a FROM clause in each SELECT with Informix. You might specify:
FROM "informix".systables WHERE tabid = 1, or
FROM sysmaster:"informix".sysdual, or
use some other technique to ensure that the SELECT has a FROM clause but only generates one row of data.
In my databases, I have either a table dual with a single row in it, or a synonym dual that is a synonym for sysmaster:"informix".sysdual. You can get away without the "informix". part of those statements if the database is 'normal'; the owner name is crucial if your database is an Informix MODE ANSI database.
In some versions of Infomix you can build a virtual table using the TABLE keyword followed by a value of one of the COLLECTION data types, such as a LIST collection. In your case, use a LIST of values of Unnamed Row type using the ROW(...) constructor syntax.
Creating a TABLE from COLLECTION value
http://www.ibm.com/support/knowledgecenter/SSGU8G_11.50.0/com.ibm.sqls.doc/ids_sqs_1375.htm
ROW(...) construction syntax, for literals of Unnamed Row data type
http://www.ibm.com/support/knowledgecenter/SSGU8G_11.50.0/com.ibm.sqlr.doc/ids_sqr_136.htm
Example:
select *
from TABLE(LIST{
ROW('7662', 232, 297.26),
ROW('7662', 232, 297.26)
}) T(external_id, int_id, cost_amount)
into temp mytmptable with no log
In the above, the data types are implied by the value, but when needed you can explicitly cast each value to the desired data type in the row constructor, like so:
ROW('7662'::char(10), 232::integer, 297.26::decimal(10,2))
You can also insert multiple rows by storing the values in an external file and executing the following statement in dbaccess:
LOAD FROM "externalfile" INSERT INTO mytmptable;
However, the values would have to be DELIMITED by a pipe "|" symbol, or whatever you set the DBDELIMITER environment variable to be.
If you're using the pipe delimiter, the data in your external file would look like:
7662|232|297.26|
7663|233|297.27|
...
NOTE that the data in the external file must be properly formatted or able to be converted to successfully be inserted into each mytmptable.column datatype.
Here is a simple solution fro bulk insert with SELECT part solving the rest
INSERT INTO cccmte_pp
( cmte, pref, nro, eje, id_tri, id_cuo, fecha, vto1, vto2, id_tit, id_suj, id_bie, id_gru )
SELECT * FROM TABLE (MULTISET {
row('RC', 4, 10, 2020, 1, 5, MDY(05,20,2020), MDY(05,20,2020),MDY(05,27,2020),101, 1, 96, 1 ),
row('RC', 4, 11, 2020, 1, 5, MDY(05,20,2020), MDY(05,20,2020),MDY(05,27,2020),101, 1, 96, 1 ) })
AS t( cmte, pref, nro, eje, id_tri, id_cuo, fecha, vto1, vto2, id_tit, id_suj, id_bie, id_gru )
;

SQL Command to execute multiple times?

I have situations that I need to write multiple rows of the same value to setup some tables. Say I have to add 120 rows with two columns populated. I am looking for a shortcut, instead of having the Insert line repeated n times. How to do this?
In SQL Server Management Studio, you can use the "GO" keyword with a parameter:
INSERT INTO YourTable(col1, col2, ...., colN)
VALUES(1, 'test', ....., 25)
GO 120
But that works only in Mgmt Studio (it's not a proper T-SQL command - it's a Mgmt Studio command word).
Marc
How about
Insert Table( colsnames )
Select Top 120 #value1, #Value2, etc.
From AnyTableWithMoreThan120Rows
Just make sure the types of the values in the #Value list matches the colNames List
what about
insert into tbl1
(col1,col2)
(select top 120 #value1,#value2 from tbl2)
if in sql server 2008 . new in sql server 2008 to insert into a table multiple rows in a single query .
insert into tbl1
(col1,col2)
values
(#value1,#value2),(#value1,#value2),.....(#value1,#value2)
Put the values in an unused table for safe keeping. From there you can insert from this table to the tables you need to setup.
Create an Excel Spreadsheet with your data.
Import the speadsheet into Sql Server.
You can even try with something like this(just an example)
declare #tbl table(col1 varchar(20),col2 varchar(20))
; with generateRows_cte as
(
select
1 as MyRows
union all
select
MyRows+1
from generateRows_cte
where MyRows < 120
)
insert into #tbl(col1,col2)
select
'col1' + CAST(MyRows as varchar),'col2' + CAST(MyRows as varchar)
from generateRows_cte OPTION (MAXRECURSION 0)
select * from #tbl
Note:- Why not you are trying with Bulk insert into SqlServer from a dataset ? I didnot notice first that u have a front end too(VB)!