Insert into a table several values in a temp table - sql-server

I have several values in a temp table called #tempIQ and I want to insert into a table called IQGroups using the same Group identifier. Assuming everyone has a unique IQ:
create table #tempIQ
(
id int
)
declare #GroupIDas int
set #GroupID=1001
select iq from #tempIQ
1,2,86,99,101,165,180,201
I want to insert these ids from the temp table into a grouping called IQGroups but am having difficulty finding a simple solution.
-- now try and insert all the iqs for a group into the IQGroups table from the #tempIQ table.
insert into IQGroups (GroupID, IQ) values (#GroupID, #tempiQ.iq)

Try this:
INSERT INTO IQGroups (GroupID, IQ)
SELECT #GroupID, IQ
FROM #tempIQ

Try using the SELECT statement.
INSERT INTO IQGroups (GroupID, IQ)
SELECT #GroupID, iq
FROM #tempIQ
This is the standard way to select multiple rows.

this is another way to do this,
select id, 1001 as GroupID
into IQGroups
from #tempIQ

Related

Query table-per-month data without dynamic SQL

A vendor, in their infinite wisdom, has decided to split a holidays dataset by month into separate tables i.e.
holidayPlanner.dbo.holiday_201802
holidayPlanner.dbo.holiday_201803
holidayPlanner.dbo.holiday_201804
holidayPlanner.dbo.holiday_201805
These tables are generated by the system as soon as an employee requests a holiday in the month. I can write a query that uses dynamic SQL to create a UNION query that I can work with.
Is there any way this can be done without dynamic SQL? Ideally, so I can create a table-valued-function to get the results?
you could use a table function that returns as the result the values obtained in each of the tables to be identified (you could do a search by months)
I leave the following example:
CREATE FUNCTION [dbo].[ufnHolidays]()
RETURNS #holidays TABLE
(
id int
)
AS
BEGIN
/* example data
CREATE TABLE #holiday_201802 (id int)
CREATE TABLE #holiday_201803 (id int)
CREATE TABLE #holiday_201804 (id int)
INSERT #holiday_201802 VALUES (1)
INSERT #holiday_201803 VALUES (2)
INSERT #holiday_201804 VALUES (3)
*/
IF OBJECT_ID('tempdb.dbo.#holiday_201802') IS NOT NULL
INSERT #holidays
SELECT id FROM #holiday_201802
IF OBJECT_ID('tempdb.dbo.#holiday_201803') IS NOT NULL
INSERT #holidays
SELECT id FROM #holiday_201803
IF OBJECT_ID('tempdb.dbo.#holiday_201804') IS NOT NULL
INSERT #holidays
SELECT id FROM #holiday_201804
RETURN;
END;
GO

Inserting data from two temp tables into single table

I have payment table and Claim table and TmpProcessClaims table with the following columns in each table \
Claim : ClaimID pk, paymentID (FK),EPPID,Claimnumber,GroupNumber, certificate number
Payment : paymentID (pk),EPPID, checkDate
TmpProcessClaims: TmpProcessClaimsID(pk),EPPID, ClaimNumber,Administrator,GroupNumber,
here is what i need to do... I need to take the EPPID from TmpProcessClaims and search the same EPPID in payments table and if results are there in payment table i need to insert the results into claim table from both tables payments and TmpProcessClaims
CREATE PROCEDURE [dbo].[InsertClaims]
AS
BEGIN
CREATE TABLE #TEMPEPPID ([EPPID] VARCHAR(150), [PaymentID] BIGINT)
CREATE TABLE #TEMPCLAIM ([EPPID] VARCHAR(150), [GroupNumber] varchar(10),[ClaimNumber] varchar(50), [CertificateNumber] varchar(15))
SELECT EPPID , PaymentID
INTO #TEMPEPPID
FROM DBO.Payment
SELECT EPPID, [GroupNumber],[ClaimNumber],[CertificateNumber]
INTO #TEMPCLAIM
FROM [dbo].[TmpProcessClaimsToMedPay]
where EPPID in (select EPPID from #TEMPEPPID)
INSERT INTO Claim ....
END
GO
But i am not sure how to insert the data from two temp table into single table
is this is correct way to proceed or any other ways to go through this criteria
could any one pls help on this issue ..
many thanks in advance ...
Just join the tables and insert:
INSERT INTO Claim([column names])
SELECT [column names]
FROM DBO.Payment AS p
INNER JOIN [dbo].[TmpProcessClaimsToMedPay] AS c
where p.EPPID = c.EPPID

How to get ID from one table and associate with record in another table in SQL Server

I've tried searching for the answer to this one to no avail. There is no good logic behind the way this was setup. The guy does not know what he's doing, but it's what I have to work with (long story).
I'm using SQL Server 2008R2 I need to take records from one table and transfer the data to 4 separate tables all with a one to one relationship (I know - not smart). I need to get the value from the Identity field in the first table the data is inserted into, then populate the other 3 tables with the same ID and disperse the data accordingly. for example:
OldTable: Field1, Field2, Field3, Field4
NewTable1: Identity field, Field1
NewTable2: ID, Field2
NewTable3: ID, Field3
NewTable4: ID, Field4
I'd like to handle this in a stored procedure. I'd like to do a loop, but I read that loops in SQL are inadvisable.
Loop moving through each record in OldTable... (??)
INSERT INTO NewTable1
(Field1)
Select Field1 from OldTable
INSERT INTO NewTable2
(ID, Field2)
Select SCOPE_IDENTITY?, Field2 From OldTable Where OldTable.ID = ??
etc for other 2 tables
Loop to next record in OldTable
I am not sure how to use SCOPE_IDENTITY, but I have a feeling this will be involved in how I accomplish this.
Also, I'm probably going to need to setup a trigger for whenever a new record is created in NewTable1. I know, it's insanity, but I can't do anything about it, just have to work around it.
So, I need to know
1: the best way to initially populate the tables
2: how to make triggers for new records
The solution to 1 might involve 2.
Please help!
You can use the output clause of the merge statement to get a mapping between the existing primary key in OldTable and the newly generated identity ID in NewTable1.
-- Temp table to hold the mapping between OldID and ID
create table #ID
(
OldID int primary key,
ID int
);
-- Add rows to NewTable1 and capture the ID's in #ID
merge NewTable1 as T
using OldTable as S
on 1 = 0
when not matched by target then
insert(Field1) values(S.Field1)
output S.ID, inserted.ID into #ID(OldID, ID);
-- Add rows to NewTable2 using #ID to get the correct value for each row
insert into NewTable2(ID, Field2)
select I.ID, O.Field2
from #ID as I
inner join OldTable as O
on I.OldID = O.ID
insert into NewTable3(ID, Field3)
select I.ID, O.Field3
from #ID as I
inner join OldTable as O
on I.OldID = O.ID
insert into NewTable4(ID, Field4)
select I.ID, O.Field4
from #ID as I
inner join OldTable as O
on I.OldID = O.ID
drop table #ID;
SQL Fiddle
See also Using merge..output to get mapping between source.id and target.id
How about using the OUTPUT clause of the insert statement? Assuming that Field1 is a unique key on the OldTable...
Declare #IDinserted table(ID int, Field1 varchar(255));
Insert Into NewTable1(Field1)
Output inserted.ID, inserted.Field1 into #IDinserted
Select OldID, Field1 from OldTable;
Insert Into NewTable2(RowID, Field2)
Select i.ID, o.#Field2
from #IDinserted i Inner Join OldTable o
on i.Field1=o.Field1;

Insert records into table in SQL server

Is there a way in SQL SERVER(05 & 08) that I can insert records from an external file into a temp table? I do not have privilege to the database at all. Here is what i tried to do:
CREATE table #temp
(KEY_ID INT)
INSERT INTO #temp
SELECT 90883000
Ran #temp table with result:
KEY_ID
---------
90883000
It kind of works with just one record. How do I do if I have hundred records? Thanks a lot!!!
This just to show how to add multiple rows in a table.
CREATE table #temp(
KEY_ID integer
)
Declare #i as int
set #i = 1
WHILE (#i <= 10000)
BEGIN
insert into #temp values(#i)
set #i += 1
End
How about a table variable. I believe that the #temp need rights to the tempdb database. I believe that a table variable is used just like any other variable which is session based.
To declare a table variable:
DECLARE #ProductTotals TABLE
(
ProductID int,
Revenue money
)
Insert into a table variable:
INSERT INTO #ProductTotals (ProductID, Revenue)
SELECT ProductID, SUM(UnitPrice * Quantity)
FROM [Order Details]
GROUP BY ProductID
For importing files, you can use BULK IMPORT. Use this to get the data into your temp table, then you can run set based operations against it.
A more effective way of inserting a lot of rows.
INSERT INTO #temp
(KeyID)
SELECT TOP 1000 -- PUT YOUR QUANTITY HERE
IDENTITY(INT,1,1) AS N
FROM Master.dbo.SysColumns sc1,
Master.dbo.SysColumns sc2
If you're going to be using this a lot, just ask them to create you a TALLY TABLE.
This is how I usually do it if I have the values in a file somewhere. Inserting hundreds of records from flat text file into temp table. My example only has one column, but as long as the flat file is delimited somehow, you can do as many columns as needed. Need to make sure you put the text file in a directory you have access to.
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable
CREATE TABLE #TempTable(Col1 varchar(10)) --Specify temp-table name & columns
BULK INSERT #TempTable
FROM 'C:\FileName.txt' --Specify file path/name
WITH (
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
);
GO

SELECT INTO a table variable in T-SQL

Got a complex SELECT query, from which I would like to insert all rows into a table variable, but T-SQL doesn't allow it.
Along the same lines, you cannot use a table variable with SELECT INTO or INSERT EXEC queries.
http://odetocode.com/Articles/365.aspx
Short example:
declare #userData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
)
SELECT name, location
INTO #userData
FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30
The data in the table variable would be later used to insert/update it back into different tables (mostly copy of the same data with minor updates). The goal of this would be to simply make the script a bit more readable and more easily customisable than doing the SELECT INTO directly into the right tables.
Performance is not an issue, as the rowcount is fairly small and it's only manually run when needed.
...or just tell me if I'm doing it all wrong.
Try something like this:
DECLARE #userData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
);
INSERT INTO #userData (name, oldlocation)
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;
The purpose of SELECT INTO is (per the docs, my emphasis)
To create a new table from values in another table
But you already have a target table! So what you want is
The INSERT statement adds one or more new rows to a table
You can specify the data values in the
following ways:
...
By using a SELECT subquery to specify
the data values for one or more rows,
such as:
INSERT INTO MyTable
(PriKey, Description)
SELECT ForeignKey, Description
FROM SomeView
And in this syntax, it's allowed for MyTable to be a table variable.
You can also use common table expressions to store temporary datasets. They are more elegant and adhoc friendly:
WITH userData (name, oldlocation)
AS
(
SELECT name, location
FROM myTable INNER JOIN
otherTable ON ...
WHERE age>30
)
SELECT *
FROM userData -- you can also reuse the recordset in subqueries and joins
You could try using temporary tables...if you are not doing it from an application. (It may be ok to run this manually)
SELECT name, location INTO #userData FROM myTable
INNER JOIN otherTable ON ...
WHERE age>30
You skip the effort to declare the table that way...
Helps for adhoc queries...This creates a local temp table which wont be visible to other sessions unless you are in the same session. Maybe a problem if you are running query from an app.
if you require it to running on an app, use variables declared this way :
DECLARE #userData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
);
INSERT INTO #userData
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;
Edit: as many of you mentioned updated visibility to session from connection. Creating temp tables is not an option for web applications, as sessions can be reused, stick to temp variables in those cases
Try to use INSERT instead of SELECT INTO:
DECLARE #UserData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
)
INSERT #UserData
SELECT name, oldlocation
First create a temp table :
Step 1:
create table #tblOm_Temp (
Name varchar(100),
Age Int ,
RollNumber bigint
)
**Step 2: ** Insert Some value in Temp table .
insert into #tblom_temp values('Om Pandey',102,1347)
Step 3: Declare a table Variable to hold temp table data.
declare #tblOm_Variable table(
Name Varchar(100),
Age int,
RollNumber bigint
)
Step 4: select value from temp table and insert into table variable.
insert into #tblOm_Variable select * from #tblom_temp
Finally value is inserted from a temp table to Table variable
Step 5: Can Check inserted value in table variable.
select * from #tblOm_Variable
OK, Now with enough effort i am able to insert into #table using the below :
INSERT #TempWithheldTable SELECT
a.SuspendedReason,
a.SuspendedNotes,
a.SuspendedBy ,
a.ReasonCode FROM OPENROWSET( BULK 'C:\DataBases\WithHeld.csv', FORMATFILE =
N'C:\DataBases\Format.txt',
ERRORFILE=N'C:\Temp\MovieLensRatings.txt'
) AS a;
The main thing here is selecting columns to insert .
One reason to use SELECT INTO is that it allows you to use IDENTITY:
SELECT IDENTITY(INT,1,1) AS Id, name
INTO #MyTable
FROM (SELECT name FROM AnotherTable) AS t
This would not work with a table variable, which is too bad...

Resources