SQL Command to execute multiple times? - sql

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)!

Related

sql query to create a table at runtime and insert the values in it from the select statement from the database

what i am tryin to do is make a table(#tbl) runtime and insert the data from the select statement from the database,as what i have done so far is
declare #tbl TABLE (
Item int
)
begin
insert into #tbl values select cid from tbl_custumer where cus_ph like '%'+'987'+'%'
select * from #tbl
end
as "select cid" statement returns multiple records
I think you might want the code to look like this:
begin
declare #tbl TABLE (
Item int
);
insert into #tbl(Item)
select cid
from tbl_custumer
where cus_ph like '%'+'987'+'%';
select *
from #tbl;
end;
Notes:
The begin/end block is not really necessary, but I'm guessing you want it for other reasons (a stored procedure, if, or something similar).
The values keyword is not needed when using insert . . . select.
Use semicolons at the end of each SQL statement. Although they are optional, they make the code easier to follow.

How to validate/restrict values in a column as per a specific format in a sql Database

I am working on an application that populates values from sql Database in a format two numeric and alpha character e.g 11G,34H. There is no validation or check for the same.I want to put put checkpoint/validation from Database end.Is it possible to implement via SQL procedure or anything.Can anyone help me with the code.
Try the below query
DECLARE #strtable TABLE (column1 VARCHAR(50))
INSERT INTO #strtable
VALUES ('11H'),('sda'),('175HH'),('1H1'),('282')
INSERT INTO YourTable (Column1)
SELECT Column1
FROM #strtable
WHERE LEN(column1)=3
AND ISNUMERIC(LEFT(column1,2))=1
AND ISNUMERIC(RIGHT(column1,1))!=1
--Output : 11H

SQL Server – inserting multiple rows with single (ANSI style) statement

I am using following method for inserting multiple rows using a single INSERT statement, that is the ANSI style of inserting rows. It is available in SQL Server 2008 and 2012. I am not sure of SQL Server 2005/ 2000.
Create test table:
create table TestInsert (ID INT, Name NVARCHAR(50))
Single INSERT statement to insert 5 rows
INSERT INTO TestInsert
VALUES (1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
Please let me know if there is any other best way to achieve this
Try this instead:
INSERT TestInsert
SELECT 1, 'a'
UNION ALL
SELECT 2, 'b'
UNION ALL
SELECT 3, 'c'
UNION ALL
SELECT 4, 'd'
UNION ALL
SELECT 5, 'e'
SQL Server - inserting multiple rows with single (ANSI style) statement
For SQL Server 2000+
According to SQL The Complete Reference, Third Edition (August 12, 2009):
1) The syntax for multirow INSERTs is
INSERT INTO table-name (columns not mandatory)
query
(page 236, Figure 10-3).
2) The SELECT statement has the FROM clause mandatory (page 87, Figure 6-1).
So, in this case, to insert multiple rows using just one INSERT statement we need an auxiliary table with just one row:
CREATE TABLE dual(value INT PRIMARY KEY CHECK(value = 1))
INSERT dual(value) VALUES(1)
and then
INSERT INTO table-name (columns) -- the columns are not mandatory
SELECT values FROM dual
UNION ALL
SELECT another-values FROM dual
UNION ALL
SELECT another-values FROM dual
Edit 2: For SQL Server 2008+
Starting with SQL Server 2008 we can use row constructors: (values for row 1), (values for row 2), (values for row 3), etc. (page 218).
So,
INSERT INTO TestInsert
VALUES (1,'a'), --The string delimiter is ' not ‘...’
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
will work on SQL Server 2008+.

Not in In SQL statement?

I have set of ids in excel around 5000 and in the table I have ids around 30000. If I use 'In' condition in SQL statment I am getting around 4300 ids from what ever I have ids in Excel. But If I use 'Not In' with Excel id. I have getting around 25000+ records. I just to find out I am missing with Excel ids in the table.
How to write sql for this?
Example:
Excel Ids are
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
Table has IDs
1,
2,
3,
4,
6,
8,
9,
11,
12,
14,
15
Now I want get 5,7,10 values from Excel which missing the table?
Update:
What I am doing is
SELECT [GLID]
FROM [tbl_Detail]
where datasource = 'China' and ap_ID not in (5206896,
5206897,
5206898,
5206899,
5117083,
5143565,
5173361,
5179096,
5179097,
5179150)
Try this:
SELECT tableExcel.ID
FROM tableExcel
WHERE tableExcel.ID NOT IN(SELECT anotherTable.ID FROM anotherTable)
Here's an SQL Fiddle to try this: sqlfiddle.com/#!6/31af5/14
You're probably looking for EXCEPT:
SELECT Value
FROM #Excel
EXCEPT
SELECT Value
FROM #Table;
Edit:
Except will
treat NULL differently(NULL values are matching)
apply DISTINCT
unlike NOT IN
Here's your sample data:
declare #Excel Table(Value int);
INSERT INTO #Excel VALUES(1);
INSERT INTO #Excel VALUES(2);
INSERT INTO #Excel VALUES(3);
INSERT INTO #Excel VALUES(4);
INSERT INTO #Excel VALUES(5);
INSERT INTO #Excel VALUES(6);
INSERT INTO #Excel VALUES(7);
INSERT INTO #Excel VALUES(8);
INSERT INTO #Excel VALUES(9);
INSERT INTO #Excel VALUES(10);
declare #Table Table(Value int);
INSERT INTO #Table VALUES(1);
INSERT INTO #Table VALUES(2);
INSERT INTO #Table VALUES(3);
INSERT INTO #Table VALUES(4);
INSERT INTO #Table VALUES(6);
INSERT INTO #Table VALUES(8);
INSERT INTO #Table VALUES(9);
INSERT INTO #Table VALUES(11);
INSERT INTO #Table VALUES(12);
INSERT INTO #Table VALUES(14);
INSERT INTO #Table VALUES(15);
Import your excel file into SQL Server using the Import Data Wizard found in SQL Server Management Studio.
Then you can write the following query to find any IDs which are in the file but not in the table:
SELECT id
FROM imported_table
WHERE id NOT IN (SELECT id FROM db_table)
You should move excel data to a table in SQL Server, and then do the query in SQL Server.
select distinct id from Excel where id not in (select your ids from Sqltable)
(Obviously select your ids from Sqltable is a select which returns the Ids existing on SQL Server).
You may think that moving data to SQL Server is hard to do, but, on the contrary, it's very easy:
1) create a table
CREATE TABLE ExcelIds (Id int)
2) add a new column in excel with the following formula:
="insert into ExcelIds values(" & XX & ")"
where XX is the reference to the cell in the column with excel Ids.
3) copy the "inserts" from Excel into SSMS or whatever tool you're usin in SQL Server, and execute them.
Now you have 2 tables in SQL Server, so that querying it is absolutely easy.
When you're over, just drop the table
DROP TABLE ExcelIds
NOTE: I didn't create a key on SQL Server table because I suppose that the Ids can be repeated. Neither is justified to create a more complex SQL Query to avoid duplicates in ExcelIds for this ad hoc solution.

Using cast in insert statement

I am inserting some raw data into a table in MS SQL 2005 from excel.
Some of these data are not formatted correctly ie the amount colum is formatteT as a number 12345 whereas i need to be like 123.45 so i use this
CAST(TRANSACTION_HISTORY.AMOUNT AS decimal) / 100
to convert it correctly.
However is there a way to use the cast in an insert statement??
thanks
You can use CAST in any kind of statement(Insert, update, delete, select) where you use data.
Insert into table1 values( CAST(col1 as nvarchar(50)) )
I assume you're using a linked server or openquery to get the data from excel. You can cast in the select statement.
So
INSERT INTO YourTable
SELECT Cast(Transaction_History.Amount AS Decimal)/100
FROM EXCELLINK...[$Sheet1]
You could also just update all values in the table after you do the import
UPDATE YourTable
SET YourColumn = YourColumn/100