Selection order for an Insert Into SQL Server 2008 R2 - sql

I have a query in which I create a table and then insert data into it. My question is this, I have one column where I need to make the data distinct, my output seems to be working correctly but I would like clarification on if this is an acceptable practice.
Here is what my query looks like:
DECLARE #T1 TABLE(
MRN VARCHAR(20)
, [ENCOUNTER] VARCHAR(200)
, ...
, ...
, ...
)
INSERT INTO #T1
SELECT
A.Med_Rec_No
, A.[VISIT ID]
, ...
, ...
, ...
)
FROM (
SELECT DISTINCT PAV.PTNO_NUM AS [VISIT ID] -- MUST I CHANGE THE ORDER?
, PAV.Med_Rec_No -- MUST I CHANGE THE ORDER?
, ...
, ...
, ...
)
Does the INSERT INTO #T1 SELECT take care of the ordering for me, meaning does it really matter what order I SELECT items in the FROM statement as long as my INSESRT INTO matches what my DECLARE #T1 TABLE says?
Thank you,

When doing INSERT INTO FROM SELECT you MUST match order of columns in SELECT statement as they are in INSERT statement.
Now on other hand you not required to match column order in INSERT statement to what is in CREATE TABLE.
It is always recommended to specify COLUMN in INSERT statement. Otherwise you assuming that what you selecting matches column order in table that you are inserting into.
In your case you should modify your query like so.
INSERT INTO #T1 (MRN, Encounter)
SELECT
A.Med_Rec_No
, A.[VISIT ID]
, ...
, ...
, ...
)
FROM (
SELECT DISTINCT PAV.PTNO_NUM AS [VISIT ID]
, PAV.Med_Rec_No
, ...
, ...
, ...
)
as alternative you can modify order of column in INSERT clause
INSERT INTO #T1 (Encounter,MRN)
SELECT
A.[VISIT ID]
,A.Med_Rec_No
, ...
, ...
, ...
)
FROM (
SELECT DISTINCT PAV.PTNO_NUM AS [VISIT ID]
, PAV.Med_Rec_No
, ...
, ...
, ...
)

Related

Find if two columns exist in another table, matched as a pair

I've seen some other questions about comparing multiple columns, but I'm not sure they fit this exact need.
I'm trying to ensure an exact pair of columns in one table exists as the exact same pair of columns in another table. The goal is to check and mark a bit column as true false if it exists.
The last part of this script returns a 1, but I'm not sure if the logic ensures the exact pair is in the second table.
Is the logic in the last part of the script comparing both tables correct?
Sample Data:
CREATE TABLE #t1
(
courseid VARCHAR(10)
,courseNumber VARCHAR(10)
)
INSERT INTO #t1(
courseid
, courseNumber
)
VALUES
(3386341, 3387691)
CREATE TABLE #t2
(
courseid VARCHAR(10)
,courseNumber VARCHAR(10)
,CourseArea VARCHAR(10)
,CourseCert VARCHAR(10)
,OtherCourseNum VARCHAR(10)
)
INSERT INTO #t2(
courseid
, courseNumber
, CourseArea
, CourseCert
, OtherCourseNum
)
VALUES
(3386341 , 3387691 , 9671 , 9671 , 233321)
,(3386341 , 3387691 , 9671 , 9671 , 233321)
,(3386342 , 3387692 , 9672 , 9672 , 233322)
,(3386342 , 3387692 , 9672 , 9672 , 233322)
,(3386343 , 3387693 , 9673 , 9673 , 233323)
,(3386343 , 3387693 , 9673 , 9673 , 233323)
SELECT
CASE WHEN courseid IN (SELECT courseid FROM #t1) AND courseNumber IN (SELECT courseNumber FROM #t2) THEN 1 ELSE 0 END AS IsCourse
FROM #t1
I would always opt for an exists correlation here as it's faster and NULL-safe
select
case when exists (
select * from #t2 t2
where t2.courseid = t1.courseId and t2.courseNumber = t1.courseNumber
) then 1 else 0 end IsCourse
from #t1 t1;
No, your query doesn't correlate the id & number so your query will return a positive if the id exists anywhere in t2 and the number exists anywhere in t2, but doesn't confirm they exist on the same row. You want EXISTS e.g.
SELECT
CASE WHEN EXISTS (
SELECT 1
FROM #t2 t2
WHERE t2.courseid = t1.courseid
AND t2.courseNumber = t1.courseNumber
) THEN 1 ELSE 0 END AS IsCourse
FROM #t1 t1;

i want copy data from table to another without duplicate using triggers

i have two tables
in table number one it's add rows every moment depend on user insert
and in table number two i want to copy every row has been added on table one but with specific criteria
and also table number two have some additional columns i need them later
i want do that by triggers but i don't know how to do that
i'v already try stored procedure but not automatically
INSERT INTO ax.RETAILTRANSACTIONSALESTRANS2
(
[BARCODE]
, [CREATEDDATETIME]
,[Name]
, [ITEMID]
, [NETAMOUNTINCLTAX]
, [QTY]
, [STAFFID]
, [TERMINALID]
, [TRANSDATE]
,[PERIODICPERCENTAGEDISCOUNT]
,[ReceiptID]
)
SELECT ab.[BARCODE]
, ab.[CREATEDDATETIME]
,[ax].[ECORESPRODUCTTRANSLATION].[NAME]
, ab.[ITEMID]
, ab.[PRICE]
, ab.[QTY]
, ab.[STAFFID]
, ab.[TERMINALID]
, ab.[TRANSDATE]
, ab.[PERIODICPERCENTAGEDISCOUNT]
,ab.RECEIPTID
FROM ax.RetailTransactionSalesTrans ab
inner join [ax].[INVENTTABLE] on ab.[ITEMID] =[ax].[INVENTTABLE].[ITEMID]
inner join [ax].[ECORESPRODUCTTRANSLATION] on [ax].[INVENTTABLE].PRODUCT =[ax].[ECORESPRODUCTTRANSLATION].[PRODUCT]
LEFT JOIN ax.RETAILTRANSACTIONSALESTRANS2 a ON
a.[BARCODE] = ab.[BARCODE]
AND a.[CREATEDDATETIME] = ab.[CREATEDDATETIME]
AND a.[ITEMID] = ab.[ITEMID]
AND a.[NETAMOUNTINCLTAX] = ab.[PRICE]
AND a.[QTY] = ab.[QTY]
AND a.[STAFFID] = ab.[STAFFID]
AND a.[TERMINALID] = ab.[TERMINALID]
AND a.[TRANSDATE] = ab.[TRANSDATE]
AND a.[PERIODICPERCENTAGEDISCOUNT]=ab.[PERIODICPERCENTAGEDISCOUNT]
and a.Process=null and a.Checked=null and a.[Select]=null
where ab.[QTY]>0 and ab.[RECEIPTID]!='' and ab.[TRANSDATE] >= DATEADD(day, #daycount*-1, GetDate())
and NOT EXISTS(select * from ax.RETAILTRANSACTIONSALESTRANS2 where [CREATEDDATETIME] = ab.[CREATEDDATETIME])
i want to convert that as trigger but i don't how do that
note: #daycount i take it from another table but i pass that by my program
you can use the below and edit the needed columns , the idea is FROM Inserted you can select all rows that inserted to the main table.
CREATE TRIGGER TRetailTransactionSalesTrans ON RetailTransactionSalesTrans
FOR INSERT
AS
BEGIN
INSERT INTO RETAILTRANSACTIONSALESTRANS2
SELECT [BARCODE]
,[CREATEDDATETIME]
,[Name]
,[ITEMID]
,[NETAMOUNTINCLTAX]
,[QTY]
,[STAFFID]
,[TERMINALID]
,[TRANSDATE]
,[PERIODICPERCENTAGEDISCOUNT]
,[ReceiptID]
FROM Inserted;
END

Distinct Rows In Sql

I have a table that record events as it happens and as such could record same ID multiple times. I want to return single row for each unique RefID as 'Y' is substituted for 'N' in relevant columns. Below is a mock-up
DECLARE #Ref TABLE
(
RefID INT
, InvoiceNo INT
, InvoicedDate Date
, CustID INT
, PaidOnTime CHAR(1)
, Paidlate CHAR(1)
, PaidByCash CHAR(1)
, PaidByCard CHAR(1)
)
INSERT INTO #Ref VALUES
(23,50,'22-jun-2015', 11,'Y','N','Y','N')
, (23,50,'22-jun-2015', 11,'Y','N','N','Y')
, (27,11,'12-Aug-2015', 11,'Y','N','N','Y')
, (27,11,'22-Aug-2015', 11,'N','Y','N','Y')
, (45,67,'28-jun-2015', 11,'N','Y','Y','N')
, (45,67,'28-jun-2015', 11,'N','N','N','Y')
, (48,51,'18-jun-2015', 11,'Y','N','Y','N')
SELECT * FROM #Ref --would return values like so:
For example, RefID of 23 should be "23,50,22/06/2015,11,Y,N,Y,Y"
Group by the columns you want to be unique and use max() to get the highest value for every group (since Y is alphabetically higher than N)
SELECT RefID, InvoiceNo, InvoicedDate, CustID,
max(PaidOnTime), max(Paidlate), max(PaidByCash), max(PaidByCard)
FROM #Ref
GROUP BY RefID, InvoiceNo, InvoicedDate, CustID

SQL Server 2008 - Stored inserted IDs in a variable table for another query use later

I have an INSERT query to insert multiple records and returns a set if CompanyID that inserted, and this query is working fine. I would like to stored those returned CompanyIDs into a table variable, so I can run another query after that using those CompanyIDs. I tried, but got stuck.
Please help.
-- Create a table variable
DECLARE #CompanyIDs TABLE
(
CompanyID INT NOT NULL
)
INSERT INTO #CompanyIDs -- STUCK right here and it failed
-- This INSERT query is working fine, and will return the CompanyIDs that inserted.
INSERT INTO [Apps].[dbo].[ERP_Company]
(
[Name]
,[Type]
,[ImportFrom]
,[InActiveFlag]
,[CreatedDate]
,[CreatedBy]
,[CompanyOwnerID]
,[ModifiedDate]
,[HQAddress]
,[HQCity]
,[HQState]
,[HQZip]
,[Type2]
,[Segment]
,[Industry]
)
output inserted.CompanyID
SELECT DISTINCT(Company) AS Company
, 'End-User'
, 'MarketingUpload'
, '0'
, GETDATE()
, '1581'
, '1581'
, GETDATE()
, [Address]
, City
, [State]
, ZipCode
, 'Customer'
, Segment
, Industry
FROM dbo.Import_CompanyContact icc
WHERE RefNum = 14
AND MatchFlag = 3
AND NOT Exists (SELECT * FROM dbo.ERP_Company
WHERE REPLACE(Name, '''', '') = REPLACE(icc.Company, '''', '')
)
OUTPUT inserted.CompanyID INTO #YourTable

ORA 00937 while using INSERT INTO SELECT

When I am running the below insert into select statement, I get ORA 00937 because the below query cannot deal with one of the sub selects on APPLICATIONS table. I don't want to hardcode that value. Any suggestions?
Thanks in advance.
insert into CONFIGURATION_PARAMETER_VALUES
( ID
, NAME
, DESCRIPTION
, DATA_TYPE
, VALUE_STRING
, VALUE_INTEGER
, VALUE_DATE
, VALUE_FLOAT
, VALUE_TIMESTAMP
, APPLICATION_ID
, DELETED
)
select NVL(MAX(ID),0)+1
, 'Alert_Statuses_AllExceptNoStatus'
, 'Suspicious'
, 'String'
, 'RBS_EIM_AL_008'
, null
, null
, null
, null
, (select ID from APPLICATIONS where name = 'Rabobank v 1.0.0.0')
, 'N'
from CONFIGURATION_PARAMETER_VALUES
If it's not too late, I'd suggest implementing a SEQUENCE instead of counting. You may not get strict numeric order (there can be gaps), but you'll get a unique value every time:
CREATE SEQUENCE Config_Parm_Values_Seq START WITH <1 + your current max ID>;
Also note that your INSERT as it stands right now will behave as follows:
If there are no records in the table, it will insert nothing.
If there are records in the table, it will double the number of rows in your table every time you execute it.
So, even if you don't use the sequence, I'd consider a "plain old" INSERT instead of an INSERT ... SELECT. This example uses the sequence:
insert into CONFIGURATION_PARAMETER_VALUES
( ID
, NAME
, DESCRIPTION
, DATA_TYPE
, VALUE_STRING
, VALUE_INTEGER
, VALUE_DATE
, VALUE_FLOAT
, VALUE_TIMESTAMP
, APPLICATION_ID
, DELETED
) VALUES (
Config_Parm_Values_Seq.NEXTVAL -- Use seqname.nextval to get
-- the next value from the sequence
, 'Alert_Statuses_AllExceptNoStatus'
, 'Suspicious'
, 'String'
, 'RBS_EIM_AL_008'
, null
, null
, null
, null
, (select MAX(ID) from APPLICATIONS where name = 'Rabobank v 1.0.0.0')
, 'N')
The problem is in your SELECT statement where you are using SELECT NVL(MAX(ID), 0) + 1.
As you are using MAX function in the SELECT list, you must use a GROUP BY, which is not the solution here.
Use something like the following:
insert into CONFIGURATION_PARAMETER_VALUES
( ID
, NAME
, DESCRIPTION
, DATA_TYPE
, VALUE_STRING
, VALUE_INTEGER
, VALUE_DATE
, VALUE_FLOAT
, VALUE_TIMESTAMP
, APPLICATION_ID
, DELETED
)
select (SELECT MAX(ID) FROM configuration_parameter_values) + 1
-- above line instead of NVL(MAX(ID),0)+1
-- You can also put NVL function around the subquery.
, 'Alert_Statuses_AllExceptNoStatus'
, 'Suspicious'
, 'String'
, 'RBS_EIM_AL_008'
, null
, null
, null
, null
, (select ID from APPLICATIONS where name = 'Rabobank v 1.0.0.0')
-- Warning: The above subquery can generate a TOO_MANY_ROWS exception.
-- Use the solution in the other answer to avoid this.
, 'N'
from CONFIGURATION_PARAMETER_VALUES