Inserting data from two temp tables into single table - sql-server

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

Related

SQL trigger with IDENTITY_INSERT

I have two tables: Table1 is all the companies, Table2 is companies whose name start with A.
Table1 company (companyId int, companyName varchar(50), companySize int)
Table2 companyStartWithA (companyId int, companyName varchar(50), companySize int)
What I want to do is to create a trigger so that when I insert/update/delete something in Table1, it will automatically do the same in Table2
My code:
CREATE TRIGGER A_TRG_InsertSyncEmp
ON company
AFTER INSERT
AS
BEGIN
INSERT INTO companyStartWithA
SELECT *
FROM INSERTED
WHERE inserted.companyName LIKE 'A%'
END
And I get an error:
An explicit value for the identity column in table 'companyStartWithA' can only be specified when a column list is used and IDENTITY_INSERT is ON.
What can I do?
Thanks
The problem is the fact that you're not explicitly specifying the column in the INSERT statement, and using a SELECT * to fill the data. Both are big no-no's - you should always explicitly specify the column that you want to insert into, and you should always explicitly specify the columns that you want to select. Doing so will fix this problem:
CREATE TRIGGER A_TRG_InsertSyncEmp
ON company
AFTER INSERT
AS
BEGIN
INSERT INTO companyStartWithA (companyName, companySize)
SELECT companyName, companySize
FROM INSERTED
WHERE inserted.companyName LIKE 'A%'
END
But as Sean Lange absolutely correctly commented - this should really be just a view rather than a separate table.....
CREATE VIEW dbo.CompanyStartsWithA
AS
SELECT companyId, companyName, companySize
FROM dbo.Company
WHERE Name LIKE 'A%'
and then you don't need any messy triggers or anything - just insert into dbo.Company and all companies with a name that starts with an A will be visible in this view....

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 into a table several values in a temp table

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

SQL query taking a long time to execute

USE Pooja
GO
----Create TestTable
CREATE TABLE TestTable(RtJobCode VARCHAR(20), RtProfCode smallint,RtTestCode smallint,ProfCode smallint,TestCode smallint)
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (RtJobCode, RtProfCode,RtTestCode,ProfCode,TestCode)
SELECT RtJobCode,RtTestCode,TestCode,RtProfCode,ProfCode
FROM dbo.ResultTest,dbo.Test,dbo.Profiles
WHERE RtTestCode=ANY(Select TestCode from dbo.Test)
----Verify that Data in TestTable
SELECT *
FROM TestTable
GO
The above code tries to take out entries from a table called resutltest and profiles and test,
The problem was during creation of a cube i was encountering some data which was not consistent in all the tables,
So i tried a join on the tables but as the tables contained a huge number of columns it was'nt feasible so tried making this code which just keeps on executing without stopping
and not displaying any data
Resulttest's Rttestcode is foreign key from testcode
Your query is very slow because it is making a cartesian product between ResultTest, Test and Profiles. you need to provide "join" conditions to link the tables together.
SELECT RtJobCode
, RtTestCode
, TestCode
, RtProfCode
, ProfCode
FROM dbo.ResultTest r
JOIN dbo.Test t
ON r.RtTestCode = t.TestCode
JOIN dbo.Profiles p
ON r.RtProfCode = p.ProfCode
I speculate that this is the query you are looking for. Note the conditions that link ResultTest and Test together and the condition that links ResultTest and Profiles together.
USE Pooja
GO
----Create TestTable
CREATE TABLE TestTable(RtJobCode VARCHAR(20), RtProfCode smallint,RtTestCode smallint,RtCenCode smallint,LabNo int,ProfCode smallint,ProfRate money,ProfName varchar(100),TestCode smallint,TestRate money,TestName varchar(100),TestCategory varchar(50),Cost money)
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (RtJobCode, RtProfCode,RtTestCode,RtCenCode,LabNo,ProfCode,ProfRate,ProfName,TestCode,TestRate,TestName,TestCategory,Cost)
SELECT RtJobCode
, RtProfCode
, RtTestCode
, RtCenCode
, LabNo
, ProfCode
, ProfRate
, ProfName
, TestCode
, TestRate
, TestName
, TestCategory
, Cost
FROM dbo.ResultTest
JOIN dbo.Test
ON ResultTest.RtTestCode = Test.TestCode
JOIN dbo.Profiles
ON ResultTest.RtProfCode = Profiles.ProfCode

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