this is my PostgreSQL query. Here I pass hard coded merchant id (merchant_id = 11).but I need to dynamical pass one merchant id from set of merchant id list. but I don't Know how to pass id as a variable or array by using PostgreSQL function.
select s.enabled from loyalty_scheme L
JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid)
JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) WHERE ((SELECT demoting_time_period from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = 11)GROUP BY scheme_id)< to_char((SELECT (DATE_PART('year', CURRENT_DATE::date) - DATE_PART('year', (select max(t.date_time) As maxdat FROM loyalty_scheme L
JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid)
JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) where (T.unipoint_customer_ref_id = ( select unipoint_customer_ref_id FROM subscribe_merchant where schemerefid = (SELECT scheme_id from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = 11)GROUP BY scheme_id) ) )) ::date)) * 12 +
(DATE_PART('month', CURRENT_DATE::date) - DATE_PART('month', (select max(t.date_time) As maxdat FROM loyalty_scheme L
JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid)
JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) where (T.unipoint_customer_ref_id = ( select unipoint_customer_ref_id FROM subscribe_merchant where schemerefid = (SELECT scheme_id from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = 11)GROUP BY scheme_id) ) ))::date))),'FM999MI'))
here is other query to find list of merchant id
select array_agg(DISTINCT merchant.merchant_id)
from merchant
this are the id Array {3,6,7,11,23,32,34,40,41,43}
in first code I hard coded 11,but i need to pass all those id one by one.Is any one know how to do it. please help me to do this
finally I found the the way to do this
here is my CODE
CREATE OR REPLACE FUNCTION getdata() RETURNS CHAR AS $enables$ DECLARE enables CHAR; my_arry INTEGER[] := (
select array_agg(DISTINCT merchant.merchant_id)
from merchant
); BEGIN FOREACH my_arry SLICE 1 IN ARRAY my_arry LOOP select s.enabled INTO enables from loyalty_scheme L JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid) JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) WHERE ((SELECT demoting_time_period from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = ANY(my_arry) )GROUP BY scheme_id)< to_char((SELECT (DATE_PART('year', CURRENT_DATE::date) - DATE_PART('year', (select max(t.date_time) As maxdat FROM loyalty_scheme L JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid) JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) where (T.unipoint_customer_ref_id = ( select unipoint_customer_ref_id FROM subscribe_merchant where schemerefid = (SELECT scheme_id from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = ANY(my_arry) )GROUP BY scheme_id) ) )) ::date)) * 12 + (DATE_PART('month', CURRENT_DATE::date) - DATE_PART('month', (select max(t.date_time) As maxdat FROM loyalty_scheme L JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid) JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) where (T.unipoint_customer_ref_id = ( select unipoint_customer_ref_id FROM subscribe_merchant where schemerefid = (SELECT scheme_id from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = ANY(my_arry))GROUP BY scheme_id) ) ))::date))),'FM999MI')) ;
END LOOP; RETURN enables; END; $enables$ LANGUAGE plpgsql;
Related
I have a scenario where almost all of the tables have issues with the PK value as follows. This results is a database error or the violation of the PK insert.
When using the DBCC CheckIdent it displays an inconsistency between the next value and the current one.
Can anyone have a reason for the mismatch happening on several tables?
Since this database is then replicate, I'm afraid this error will propagate across the environment.
I adapted this script to fix it, but really trying to figure out the root of the problem.
/** Version 3.0 **/
if object_id('tempdb..#temp') is not null
drop table #temp
;
with cte as (
SELECT
distinct
A.TABLE_CATALOG AS CATALOG,
A.TABLE_SCHEMA AS "SCHEMA",
A.TABLE_NAME AS "TABLE",
B.COLUMN_NAME AS "COLUMN",
IDENT_SEED (A.TABLE_NAME) AS Seed,
IDENT_INCR (A.TABLE_NAME) AS Increment,
IDENT_CURRENT (A.TABLE_NAME) AS Curr_Value
, DBPS.row_count AS NumberOfRows
FROM INFORMATION_SCHEMA.TABLES A
inner join INFORMATION_SCHEMA.COLUMNS B on b.TABLE_NAME = a.TABLE_NAME and b.TABLE_SCHEMA = a.TABLE_SCHEMA
inner join sys.identity_columns IC on OBJECT_NAME (IC.object_id) = a.TABLE_NAME
inner join sys.dm_db_partition_stats DBPS ON DBPS.object_id =IC.object_id
inner join sys.indexes as IDX ON DBPS.index_id =IDX.index_id
WHERE A.TABLE_CATALOG = B.TABLE_CATALOG AND
A.TABLE_SCHEMA = B.TABLE_SCHEMA AND
A.TABLE_NAME = B.TABLE_NAME AND
COLUMNPROPERTY (OBJECT_ID (B.TABLE_NAME), B.COLUMN_NAME, 'IsIdentity') = 1 AND
OBJECTPROPERTY (OBJECT_ID (A.TABLE_NAME), 'TableHasIdentity') = 1 AND
A.TABLE_TYPE = 'BASE TABLE'
)
select 'DBCC CHECKIDENT ('''+A.[SCHEMA]+'.'+a.[TABLE]+''', reseed)' command
, ROW_NUMBER() OVER(ORDER BY a.[SCHEMA], a.[TABLE] asc) AS ID
, A.Curr_Value
, a.[TABLE]
into #temp
from cte A
ORDER BY A.[SCHEMA], A.[TABLE]
declare #i int = 1, #count int = (select max(ID) from #temp)
declare #text varchar(max) = ''
select #COUNT= count(1) FROM #temp
WHILE #I <= #COUNT
BEGIN
SET #text = (SELECT command from #temp where ID=#I)
EXEC (#text + ';')
print #text
select Curr_Value OldValue, ident_current([TABLE]) FixValue, [TABLE] from #temp where ID=#I
SET #I = #I + 1
SET #text='';
END
go
maybe someone or something with enough permissions made a mistake by reseeding?
As simple as this:
create table testid (
id int not null identity (1,1) primary key,
data varchar (3)
)
insert into testid (data) values ('abc'),('cde')
DBCC CHECKIDENT ('testid', RESEED, 1)
insert into testid (data) values ('bad')
I have procedure like this and I get error in If clause. I think it is because COUNT. But my clause have to be like that so I don't know how to solve it. Maybe it would be good to create a function or something similar. Rest of the code is okay
CREATE PROCEDURE DohvatiSveUgovore #zavodId int
AS
BEGIN
DECLARE #TempUgovori TABLE
(
Id int,
UstrojstvenaJedinica nvarchar(100),
VrstaUgovora nvarchar(100),
KlasaUgovora nvarchar(100),
UrudzbeniBrojUgovora nvarchar(100),
DatumPocetkaUgovora nvarchar(10),
DatumIstekaUgovora nvarchar(10)
)
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
if( (SELECT COUNT(UstrojstvenaJedinicaId) FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS') = 1)
begin
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS')
end
ELSE
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE Isdeleted = 0 and UstrojstvenaJedinicaId = #zavodId)
end
ERROR is here in Group by and I don't know why.
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora
SELECT
tu.Id,
tu.UstrojstvenaJedinica AS 'UstrojstvenaJedinica',
tu.VrstaUgovora AS 'VrstaUgovora',
tu.KlasaUgovora AS 'KlasaUgovora',
tu.UrudzbeniBrojUgovora AS 'UrudzbeniBrojUgovora',
tu.DatumIstekaUgovora AS 'DatumPocetkaUgovora',
tu.DatumIstekaUgovora AS 'DatumIstekaUgovora',
ISNULL(STRING_AGG(LTRIM(RTRIM(p.Naziv)), ', '), '') as 'Partner'
FROM #TempUgovori AS tu
LEFT JOIN VezaUgovorPartner AS vup
on tu.Id = vup.UgovorId
LEFT JOIN [TEST_MaticniPodaci2].dbo.Partner as p
ON vup.PartnerId = p.PartnerID
GROUP BY tu.Id, tu.UstrojstvenaJedinica, tu.VrstaUgovora, tu.KlasaUgovora, tu.UrudzbeniBrojUgovora, tu.DatumPocetkaUgovora, tu.DatumIstekaUgovora
END
EXEC [TEST_Ugovori_Prod].[dbo].[DohvatiSve] 6;
GO
I am sorry for too much code but without it I can't run query.
It looks like you're trying to tell SQL Server to join to VezaUgovorUstrojstvenaJedinica differently depending on the circumstances. The sql engine can't figure that out. For a very brief discussion on how sql evaluates a query, here's a start:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/70efeffe-76b9-4b7e-b4a1-ba53f5d21916/order-of-execution-of-sql-queries?forum=transactsql
Maybe something like this will work for you?
CREATE PROCEDURE DohvatiSveUgovore #zavodId int
AS
BEGIN
DECLARE #TempUgovori TABLE
(
Id int,
UstrojstvenaJedinica nvarchar(100),
VrstaUgovora nvarchar(100),
KlasaUgovora nvarchar(100),
UrudzbeniBrojUgovora nvarchar(100),
DatumPocetkaUgovora nvarchar(10),
DatumIstekaUgovora nvarchar(10)
);
DECLARE #HCPHS integer;
SELECT
#HCPHS = COUNT(UstrojstvenaJedinicaId)
FROM
VezaUgovorUstrojstvenaJedinica
WHERE
UstrojstvenaJedinicaId = 'HCPHS';
IF #HCPHS = 1
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
<JOIN OF SOME KIND>
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS')
ON <SOME CRITERIA>
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora
ELSE
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
<JOIN OF SOME KIND>
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE Isdeleted = 0 and UstrojstvenaJedinicaId = #zavodId)
ON <SOME CRITERIA>
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora
I have two tables Part and Service Entry Part. The first statement returns all parts and the second statement returns parts with a service type of 13.
What I need to do is if the second select returns a part then the record from second select should be inlcuded and that part from the first select should be be excluded
DECLARE #run_log TABLE(
[Instrument] nvarchar(max),
[SubSystem] NVARCHAR(max),
[AbPartNumber] NVARCHAR(max),
[RSLMSPartID] int,
[PartDescriptionWithParent] NVARCHAR(max),
[PartRevisionNumber] NVARCHAR(max),
[ServiceEntryID] int,
[Date] datetime,
[TSBNumber] nvarchar (max),
[CRNumber] nvarchar(max)
)
insert #run_log
-- parts with default revision number
select
System.SystemFullName as Instrument,
Part.System as SubSystem,
Part.AbPartNo as AbPartNumber,
Part.ID as RSLMSPartID,
Part.PartDescriptionWithParent,
Part.RevisionNumber as PartRevisionNumber,
NULL as ServiceEntryID,
NULL as Date,
NULL as TSBNumber,
NULL as CRNumber
from Part
inner join InstrumentType on Part.InstrumentTypeID = InstrumentType.ID
inner join SystemModule on SystemModule.InstrumentTypeID = Part.InstrumentTypeID
inner join System on System.ID = SystemModule.SystemID
WHERE ((#PlatformID =0) OR (System.PlatformID = #PlatformID) OR (#PlatformID = 12 AND System.PlatformID <= 2))
AND (#SelectedSystemID is null OR System.ID IN(select * from dbo.SplitInts_RBAR_1(#SelectedSystemID, ',')))
AND (#SelectedAbIDs is null OR Part.ID IN (select * from dbo.SplitInts_RBAR_1(#SelectedAbIDs,',')))
AND (#SelectedSubSystems is null OR Part.System IN (select * from dbo.SplitStrings_Moden(#SelectedSubSystems,',')))
AND System.Active = 1 and Part.Active = 1
ORDER BY SubSystem,RSLMSPartID
;WITH RunLogs AS(
SELECT *
FROM #run_log r
)
select * from RunLogs
UNION
select System.SystemFullName as Instrument,
Part.System as Subsystem,
Part.AbbottPartNo as AbPartNumber,
Part.ID as RSLMSPartID,
Part.PartDescriptionWithParent,
ServiceEntryPart.PartRevisionNumber AS PartRevisionNumber,
ServiceEntryPart.ServiceEntryID,
ServiceEntry.ServiceDateTime as Date,
ServiceEntry.TSBNumber,
ServiceEntry.CRNumber
from Part
inner join ServiceEntryPart on ServiceEntryPart.PartID = Part.ID
inner join ServiceEntry on ServiceEntry.ID = ServiceEntryPart.ServiceEntryID
inner join systemmodule on ServiceEntryPart.SystemModuleID = SystemModule.ID
inner join System on System.ID = SystemModule.SystemID
cross apply
dbo.SplitStrings_Moden(ServiceEntryPart.ServiceTypeIDs, N',') M2
JOIN dbo.SplitStrings_Moden('13', N',') P ON (M2.Item = P.Item)
WHERE System.Active = 1 AND Part.Active = 1
AND (#SelectedSystemID is null OR System.ID IN(select * from dbo.SplitInts_RBAR_1(#SelectedSystemID, ',')))
AND ((#PlatformID =0) OR (System.PlatformID = #PlatformID) OR (#PlatformID = 12 AND System.PlatformID <= 2))
AND (ServiceEntry.ServiceDateTime between #StartDate and #EndDate)
AND (#SelectedAbIDs is null OR Part.ID in (select * from dbo.SplitInts_RBAR_1(#SelectedAbIDs,',')))
AND (#SelectedSubSystems is null OR Part.System IN (select * from dbo.SplitStrings_Moden(#SelectedSubSystems,',')))
I am trying to develop a T-SQL query to exclude all rows from another table "B". This other table "B" has 3 columns comprising its PK for a total of 136 rows. So I want to select all columns from table "A" minus those from table "B". How do I do this? I don't think this query is correct because I am still getting a duplicate record error:
CREATE TABLE #B (STUDENTID VARCHAR(50), MEASUREDATE SMALLDATETIME, MEASUREID VARCHAR(50))
INSERT #B
SELECT studentid, measuredate, measureid
from [J5C_Measures_Sys]
GROUP BY studentid, measuredate, measureid
HAVING COUNT(*) > 1
insert into J5C_MasterMeasures (studentid, measuredate, measureid, rit)
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_14
from [J5C_Measures_Sys] A
join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_14'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
where a.score_14 is not null AND B.MEASURENAME IS NOT NULL
and (A.studentid NOT IN (SELECT studentid from #B)
and a.measuredate NOT IN (SELECT measuredate from #B)
and a.measureid NOT IN (SELECT measureid from #B))
use NOT EXISTS...NOT IN doesn't filter out NULLS
insert into J5C_MasterMeasures (studentid, measuredate, measureid, rit)
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_14
from [J5C_Measures_Sys] A
join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_14'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
where a.score_14 is not null AND B.MEASURENAME IS NOT NULL
AND NOT EXISTS (select 1 from #B where #b.studentid = A.studentid
and a.measuredate = #B.measuredate
and a.measureid = #B.measureid)
and not exists (select 1 from J5C_MasterMeasures z
where z.studentid = A.studentid)
Just so you know, take a look at Select all rows from one table that don't exist in another table
Basically there are at least 5 ways to select all rows from onr table that are not in another table
NOT IN
NOT EXISTS
LEFT and RIGHT JOIN
OUTER APLY (2005+)
EXCEPT (2005+)
Here is a general solution for the difference operation using left join:
select * from FirstTable
left join SecondTable on FirstTable.ID = SecondTable.ID
where SecondTable.ID is null
Of course yours would have a more complicated join on clause, but the basic operation is the same.
I think you can use "NOT IN" with a subquery, but you say you have a multi-field key?
I'd be thinking about using a left outer join and then testing for null on the right...
Martin.
I am trying to develop a query to just return non-duplicate records so that I can add these to my database, but I keep getting the duplicate record error.
I tried your solution but am still getting duplicate error problem. I deleted the 35 rows which were duplicate. What else could be causing this? Here is my query. Part of the confusion I think is that measureid is a single column in j5c_MasterMeasures, but this value comes from two fields in j5c_ListBoxMeasures_Sys.
CREATE TABLE #GOOD_RECORDS3 (STUDENTID VARCHAR(50), MEASUREDATE SMALLDATETIME, MEASUREID VARCHAR(100),
score_10 VARCHAR(100))
INSERT INTO #GOOD_RECORDS3
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_10
from [J5C_Measures_Sys] A join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
except
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_10
from [J5C_Measures_Sys] A join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
GROUP BY A.studentid, A.measuredate, B.measurename, B.LabelName, A.score_10
having COUNT(A.score_10) > 1
delete #GOOD_RECORDS3
from #GOOD_RECORDS3 a
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_10'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
WHERE A.SCORE_10 IS NOT NULL AND A.STUDENTID IS NOT NULL AND A.MEASUREID IS NOT NULL
and exists (select 1 from J5C_MasterMeasures M
where M.StudentID = A.StudentID
and M.MeasureID = A.MeasureID)
Insert into J5C_MasterMeasures (studentid, measuredate, measureid, nce)
select A.studentid, A.measuredate, a.MEASUREID, A.score_10
from #GOOD_RECORDS3 a
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_10'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
WHERE A.SCORE_10 IS NOT NULL AND A.STUDENTID IS NOT NULL AND A.MEASUREID IS NOT NULL
You have not menstioned the specifics of the unique constraint on J5C_MasterMeasures. Therefore, I assumed that all four columns being inserted were part of the constraint. In addition, your use of Except leads me to believe that you are using SQL Server 2005 or later. In addition, it is not clear how the join to J5C_MeasureNamesV2_Sys fits into the design or solution.
With GoodRecords As
(
Select A.StudentId
, A.measuredate
, B.measurename+ ' ' +B.LabelName
, A.score_10 As NCE
From [J5C_Measures_Sys] A
Join [J5C_ListBoxMeasures_Sys] B
On A.MeasureID = B.MeasureID
Where A.StudentId Is Not Null
And A.Score_10 Is Not Null
And A.MeasureId Is Not Null
Group By A.StudentId
, A.MeasureDate
, B.MeasureName+ ' ' +B.LabelName
, A.score_10
Having Count(A.Score_10) = 0
)
Insert J5C_MasterMeasures ( StudentId, MeasureData, MeasureId, NCE )
Select GR.StudentId, GR.MeasureData, GR.MeasureId, GR.NCE
From GoodRecords As GR
Join [J5C_MeasureNamesV2_Sys] v
On v.Score_field_id = 'Score_10'
Where Not Exists (
Select 1
From J5C_MasterMeasures As J1
Where J1.StudentId = GR.StudentId
And J1.MeasureData = GR.MeasureData
And J1.MeasureId = GR.MeasureId
And J1.NCE = GR.NCE
)