Decryption Error in Query - postgresql

I have a large query that encrypts/decrypts one table in PostgreSQL. I added a new conditional to this query and it now throws an error. The original query retrieves all records based on date and inner join relevance (all records from tblSessions that meet the conditions).
The updated query retrieves only records from tblSessions where parent_session_id is not null (any records from tblSessions that have a child record are omitted from results).
tblsessions (only showing fields that pertain to join conditions)
sessionid | decision_id | start_time | end_time | is_comlete | parent_session_id
---------------------------------------------------------------------------------
SERIAL | BYTEA | BYTEA | BYTEA | BYTEA | INTEGER DEFAULT 0
In the SQL window of Posgres, Running the second query gives me the following error:
ERROR: function decrypt(integer, "unknown", "unknown") does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You may need to add explicit type casts.
Original query (works):
SELECT z.conditionname, x.name AS domainname, d.decisionName,
c.firstname AS counselor_first_name, c.lastname AS counselor_last_name,
o.name AS organization_name,
encode(decrypt(s.start_time, '####salt####', '###encryption mode###'), 'escape') AS start_time,
encode(decrypt(s.end_time, '####salt####', '###encryption mode###'), 'escape') AS end_time,
encode(decrypt(s.is_complete, '####salt####', '###encryption mode###'), 'escape') AS is_complete,
s.parent_session_id
FROM tblDecisions d
INNER JOIN tblSessions s ON encode(decrypt(s.decision_id, '####salt####', '###encryption mode###'), 'escape') = d.decisionid
INNER JOIN tblCounselors c ON encode(decrypt(s.counselor_ck, '####salt####', '###encryption mode###'), 'escape') = c.campuskey
INNER JOIN tblCounselor_to_organization co ON co.counselor_id = c.counselorid
INNER JOIN tblOrganizations o ON o.organizationid = co.organization_id
INNER JOIN tblDomains x ON x.domainid = d.domain_id
INNER JOIN tblConditions z ON z.conditionid = x.condition_id
AND encode(decrypt(s.start_time, '####salt####', '###encryption mode###'), 'escape') >= '2012-01-01 00:00:00'
AND encode(decrypt(s.is_complete, '####salt####', '###encryption mode###'), 'escape') = 'true'
ORDER BY encode(decrypt(s.start_time, '####salt####', '###encryption mode###'), 'escape'), encode(decrypt(s.last_name, '####salt####', '###encryption mode###'), 'escape'), encode(decrypt(s.first_name, '####salt####', '###encryption mode###'), 'escape')
Revised query (doesn't work; commented additions below)
SELECT z.conditionname, x.name AS domainname, d.decisionName,
c.firstname AS counselor_first_name, c.lastname AS counselor_last_name,
o.name AS organization_name,
encode(decrypt(s.start_time, '####salt####', '###encryption mode###'), 'escape') AS start_time,
encode(decrypt(s.end_time, '####salt####', '###encryption mode###'), 'escape') AS end_time,
encode(decrypt(s.is_complete, '####salt####', '###encryption mode###'), 'escape') AS is_complete,
s.parent_session_id
//////// ADDITION START
, (SELECT MAX(encode(decrypt(start_time, '####salt####', '###encryption mode###'), 'escape')) AS start_time
FROM tblSessions s2
WHERE encode(decrypt(s2.parent_session_id, '####salt####', '###encryption mode###'), 'escape') = encode(decrypt(s.parent_session_id, '####salt####', '###encryption mode###'), 'escape') )
//////// ADDITION END
FROM tblDecisions d
INNER JOIN tblSessions s ON encode(decrypt(s.decision_id, '####salt####', '###encryption mode###'), 'escape') = d.decisionid
INNER JOIN tblCounselors c ON encode(decrypt(s.counselor_ck, '####salt####', '###encryption mode###'), 'escape') = c.campuskey
INNER JOIN tblCounselor_to_organization co ON co.counselor_id = c.counselorid
INNER JOIN tblOrganizations o ON o.organizationid = co.organization_id
INNER JOIN tblDomains x ON x.domainid = d.domain_id
INNER JOIN tblConditions z ON z.conditionid = x.condition_id
AND encode(decrypt(s.start_time, '####salt####', '###encryption mode###'), 'escape') >= '2012-01-01 00:00:00'
AND encode(decrypt(s.is_complete, '####salt####', '###encryption mode###'), 'escape') = 'true'
/////// ADDITION START
AND NOT EXISTS (
SELECT 1
FROM tblSessions s1
WHERE encode(decrypt(s1.parent_session_id, '####salt####', '###encryption mode###'), 'escape') = encode(decrypt(s.sessionid, '####salt####', '###encryption mode###'), 'escape') )
AND (
( encode(decrypt(s.parent_session_id, '####salt####', '###encryption mode###'), 'escape') IS NULL) OR
( encode(decrypt(s.start_time, '####salt####', '###encryption mode###'), 'escape') = (
SELECT MAX(encode(decrypt(start_time, '####salt####', '###encryption mode###'), 'escape')) AS start_time
FROM tblSessions s2
WHERE encode(decrypt(s2.parent_session_id, '####salt####', '###encryption mode###'), 'escape') = encode(decrypt(s.parent_session_id, '####salt####', '###encryption mode###'), 'escape')
)
)
)
///////// ADDITION END
ORDER BY encode(decrypt(s.start_time, '####salt####', '###encryption mode###'), 'escape'), encode(decrypt(s.last_name, '####salt####', '###encryption mode###'), 'escape'), encode(decrypt(s.first_name, '####salt####', '###encryption mode###'), 'escape')
I understand the error message, but that can't be the actual issue since all additions to the query have been properly decoded. Am I missing something obvious?

The question mentions that parent_session_id is type INTEGER but it is passed as the first argument to decrypt in the snippet below, unlike the rest of the code that seem to pass only bytea fields there.
decrypt(s.parent_session_id, '####salt####', '###encryption mode###')
This is likely to provokes the error mentioned, since there's no flavor of decrypt that takes an integer as the first argument (from the error message, could be confirmed with \df decrypt in psql)
Are you sure these session IDs are encrypted?

Related

How to list all constraints of a table in PostgreSQL?

How to list all constraints (Primary key, Foreign Key, check, unique mutual exclusive, ..) of a table in PostgreSQL?
Constraints of the table can be retrieved from catalog-pg-constraint. using the SELECT query.
SELECT con.*
FROM pg_catalog.pg_constraint con
INNER JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
INNER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespace
WHERE nsp.nspname = '{schema name}'
AND rel.relname = '{table name}';
and the same can be viewed in PSQL using
\d+ {SCHEMA_NAME.TABLE_NAME}
Here is POSTGRES specific answer
..... it will retrive all columns and their relationship as well
SELECT * FROM (
SELECT
pgc.contype as constraint_type,
pgc.conname as constraint_name,
ccu.table_schema AS table_schema,
kcu.table_name as table_name,
CASE WHEN (pgc.contype = 'f') THEN kcu.COLUMN_NAME ELSE ccu.COLUMN_NAME END as column_name,
CASE WHEN (pgc.contype = 'f') THEN ccu.TABLE_NAME ELSE (null) END as reference_table,
CASE WHEN (pgc.contype = 'f') THEN ccu.COLUMN_NAME ELSE (null) END as reference_col,
CASE WHEN (pgc.contype = 'p') THEN 'yes' ELSE 'no' END as auto_inc,
CASE WHEN (pgc.contype = 'p') THEN 'NO' ELSE 'YES' END as is_nullable,
'integer' as data_type,
'0' as numeric_scale,
'32' as numeric_precision
FROM
pg_constraint AS pgc
JOIN pg_namespace nsp ON nsp.oid = pgc.connamespace
JOIN pg_class cls ON pgc.conrelid = cls.oid
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = pgc.conname
LEFT JOIN information_schema.constraint_column_usage ccu ON pgc.conname = ccu.CONSTRAINT_NAME
AND nsp.nspname = ccu.CONSTRAINT_SCHEMA
UNION
SELECT null as constraint_type , null as constraint_name , 'public' as "table_schema" ,
table_name , column_name, null as refrence_table , null as refrence_col , 'no' as auto_inc ,
is_nullable , data_type, numeric_scale , numeric_precision
FROM information_schema.columns cols
Where 1=1
AND table_schema = 'public'
and column_name not in(
SELECT CASE WHEN (pgc.contype = 'f') THEN kcu.COLUMN_NAME ELSE kcu.COLUMN_NAME END
FROM
pg_constraint AS pgc
JOIN pg_namespace nsp ON nsp.oid = pgc.connamespace
JOIN pg_class cls ON pgc.conrelid = cls.oid
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = pgc.conname
LEFT JOIN information_schema.constraint_column_usage ccu ON pgc.conname = ccu.CONSTRAINT_NAME
AND nsp.nspname = ccu.CONSTRAINT_SCHEMA
)
) as foo
ORDER BY table_name desc
I wasn't able to get the above solutions to work. Maybe they're no longer supported or more likely I'm doing something wrong. This is how I got it to work. Note that the "contype" column will be abbreviated with the constraint type (e.g. 'c' for check, 'p' for primary key, etc.). I include that variable in case you want to add a WHERE statement to filter for it after the FROM block.
select pgc.conname as constraint_name,
ccu.table_schema as table_schema,
ccu.table_name,
ccu.column_name,
contype,
pg_get_constraintdef(pgc.oid)
from pg_constraint pgc
join pg_namespace nsp on nsp.oid = pgc.connamespace
join pg_class cls on pgc.conrelid = cls.oid
left join information_schema.constraint_column_usage ccu
on pgc.conname = ccu.constraint_name
and nsp.nspname = ccu.constraint_schema
order by pgc.conname;
SELECT constraint_name, table_name, column_name, ordinal_position FROM information_schema.key_column_usage WHERE table_name = 'put your table name here';

[PostgreSQL]: Subquery has too many columns

I am trying to run a query, but the result is showing the error message "Subquery has too many columns". I have to change where the clause with array to string but the error is the same. could you help me, if you have any suggestions or different queries as modify to solve this?
the query is:
create table my_schema.table_1 as select a.*
, O.ID1
, J.ID2
, K.ID3
, L.ID4
, M.ID5
, S.ID6
, O.plan_name plan_name1
, J.plan_name plan_name2
, K.plan_name plan_name3
, L.plan_name plan_name4
, M.plan_name plan_name5
, S.plan_name plan_name6
from (
select
PRD_ID
, NBR
, SI
, START_TIME
, ATTR4
, G_ID
, BYTE_UP
, BYTE_DOWN
, LIST
, TYPE_ID1
, TYPE_ID2
, TYPE_ID3
, TYPE_ID4
, TYPE_ID5
, TYPE_ID6
, CHARGE1, CHARGE2, CHARGE3, CHARGE4, CHARGE5, CHARGE6
from my_schema.source where prd_id = '20200101'
and TYPE IN (3) ) a
left outer join (select distinct id, price_plan_name from my_schema.id_ref_v9) O on split_part(split_part(list,';',1),',',1) = O.id
left outer join (select distinct id, price_plan_name from my_schema.id_ref_v9) J on split_part(split_part(list,';',2),',',1) = J.id
left outer join (select distinct id, price_plan_name from my_schema.id_ref_v9) K on split_part(split_part(list,';',3),',',1) = K.id
left outer join (select distinct id, price_plan_name from my_schema.id_ref_v9) L on split_part(split_part(list,';',4),',',1) = L.id
left outer join (select distinct id, price_plan_name from my_schema.id_ref_v9) M on split_part(split_part(list,';',5),',',1) = M.id
left outer join (select distinct id, price_plan_name from my_schema.id_ref_v9) S on split_part(split_part(list,';',6),',',1) = S.id
WHERE (
O.id in (select * from my_schema.LIST_PRICEID4)or
J.id in (select * from my_schema.LIST_PRICEID4)or
K.id in (select * from my_schema.LIST_PRICEID4)or
L.id in (select * from my_schema.LIST_PRICEID4)or
M.id in (select * from my_schema.LIST_PRICEID4)or
S.id in (select * my_schema.LIST_PRICEID4))

PG_Depend Column Alias (view) to Source Column (table) mapping dependancy

I'm using version 8.2 Postresql
Have been trying to do this for days now, and I keep hitting the same wall. How to Display the following:
Source Table || Source_column || Target View || Target Column
Stg_table1|| customerid || vw_customer || Customer_details_id
The biggest problem I have is that I can't link the Alias names in the view, back to the Source_column. This is because the Ordinal position of the columns in the Source_table, is different to the columns in the Target_view.
I have tried using these scripts, with no luck (this joins the columns back on using information schema, and Ordinal Position)
select distinct
a.attname AS SOURCE
, a.attname::information_schema.sql_identifier AS column_name
--, format_type(a.atttypid, NULL) AS Source_Type
, d.refobjid::regclass AS Source_table
, r.ev_class::regclass AS Target_View
--, pt.Typname AS TYPE, a.*
--, c.Column_name AS Target
--, c.Data_type
from pg_attribute as a
join pg_depend as d on d.refobjid = a.attrelid and d.refobjsubid = a.attnum
join pg_rewrite as r on d.objid = r.oid
--join information_schema.columns c ON a.attnum = c.ordinal_position --and r.ev_class::regclass = c.table_schema||'.'||c.table_name
--join pg_type as pt on a.atttypid = pt.oid
JOIN pg_class
ON pg_class.oid = a.attrelid
AND a.attnum > 0
where
r.ev_class = 'abc.vw_customer'::regclass
and c.table_schema||'.'||c.table_name = 'vw_customer';
And I have also tried it this way:
SELECT distinct dependent.relname, pg_attribute.attname
, pg_attrdef.*
--, pg_attribute.attname::information_schema.sql_identifier AS column_name
--, pg_depend.objid, pg_attribute.*
FROM pg_depend
JOIN pg_rewrite ON pg_depend.objid = pg_rewrite.oid
JOIN pg_class as dependee ON pg_rewrite.ev_class = dependee.oid
JOIN pg_class as dependent ON pg_depend.refobjid = dependent.oid
JOIN pg_attribute ON pg_depend.refobjid = pg_attribute.attrelid
--AND pg_depend.refobjsubid = pg_attribute.attnum
LEFT JOIN pg_attrdef ON pg_attribute.attrelid = pg_attrdef.adrelid AND pg_attribute.attnum = pg_attrdef.adnum
WHERE dependee.relname = 'vw_customer'
--and attname in ('Customer_details_id', 'customerid')
AND pg_attribute.attnum > 0

List all index names, column names and its table name of a PostgreSQL database

What is the query to get the list all index names, its column name and its table name of a postgresql database?
I have tried to get the list of all indexes in a db by using this query but how to get the list of indexes, its column names and its table names?
SELECT *
FROM pg_class, pg_index
WHERE pg_class.oid = pg_index.indexrelid
AND pg_class.oid IN (
SELECT indexrelid
FROM pg_index, pg_class
WHERE pg_class.oid=pg_index.indrelid
AND indisunique != 't'
AND indisprimary != 't'
AND relname !~ '^pg_');
This will output all indexes with details (extracted from my view definitions):
SELECT i.relname as indname,
i.relowner as indowner,
idx.indrelid::regclass,
am.amname as indam,
idx.indkey,
ARRAY(
SELECT pg_get_indexdef(idx.indexrelid, k + 1, true)
FROM generate_subscripts(idx.indkey, 1) as k
ORDER BY k
) as indkey_names,
idx.indexprs IS NOT NULL as indexprs,
idx.indpred IS NOT NULL as indpred
FROM pg_index as idx
JOIN pg_class as i
ON i.oid = idx.indexrelid
JOIN pg_am as am
ON i.relam = am.oid;
Optionally add an extra join to the end so as to trim the namespaces:
SELECT i.relname as indname,
i.relowner as indowner,
idx.indrelid::regclass,
am.amname as indam,
idx.indkey,
ARRAY(
SELECT pg_get_indexdef(idx.indexrelid, k + 1, true)
FROM generate_subscripts(idx.indkey, 1) as k
ORDER BY k
) as indkey_names,
idx.indexprs IS NOT NULL as indexprs,
idx.indpred IS NOT NULL as indpred
FROM pg_index as idx
JOIN pg_class as i
ON i.oid = idx.indexrelid
JOIN pg_am as am
ON i.relam = am.oid
JOIN pg_namespace as ns
ON ns.oid = i.relnamespace
AND ns.nspname = ANY(current_schemas(false));
More human friendly version of #Denis solution:
SELECT
U.usename AS user_name,
ns.nspname AS schema_name,
idx.indrelid :: REGCLASS AS table_name,
i.relname AS index_name,
idx.indisunique AS is_unique,
idx.indisprimary AS is_primary,
am.amname AS index_type,
idx.indkey,
ARRAY(
SELECT pg_get_indexdef(idx.indexrelid, k + 1, TRUE)
FROM
generate_subscripts(idx.indkey, 1) AS k
ORDER BY k
) AS index_keys,
(idx.indexprs IS NOT NULL) OR (idx.indkey::int[] #> array[0]) AS is_functional,
idx.indpred IS NOT NULL AS is_partial
FROM pg_index AS idx
JOIN pg_class AS i
ON i.oid = idx.indexrelid
JOIN pg_am AS am
ON i.relam = am.oid
JOIN pg_namespace AS NS ON i.relnamespace = NS.OID
JOIN pg_user AS U ON i.relowner = U.usesysid
WHERE NOT nspname LIKE 'pg%'; -- Excluding system tables
The Query to list all the indexes of a database
SELECT
tablename,
indexes [1],
indexes [2],
indexes [3],
indexes [4],
indexes [5],
indexes [6],
indexes [7],
indexes [8],
indexes [9],
indexes [10]
FROM (SELECT
tablename,
array_agg(indexname) AS indexes
FROM pg_indexes
WHERE schemaname = 'public'
GROUP BY tablename) as sub;
Here's a version that simplifies things compared to other answers by
avoiding nested selects
avoiding built-in functions (maybe hard to remember)
using LATERAL and UNNEST(...) WITH ORDINALITY features available in later PostgreSQL versions (9.4+)
SELECT
tnsp.nspname AS schema_name,
trel.relname AS table_name,
irel.relname AS index_name,
array_agg (
a.attname
|| ' ' || CASE o.option & 1 WHEN 1 THEN 'DESC' ELSE 'ASC' END
|| ' ' || CASE o.option & 2 WHEN 2 THEN 'NULLS FIRST' ELSE 'NULLS LAST' END
ORDER BY c.ordinality
) AS columns
FROM pg_index AS i
JOIN pg_class AS trel ON trel.oid = i.indrelid
JOIN pg_namespace AS tnsp ON trel.relnamespace = tnsp.oid
JOIN pg_class AS irel ON irel.oid = i.indexrelid
CROSS JOIN LATERAL unnest (i.indkey) WITH ORDINALITY AS c (colnum, ordinality)
LEFT JOIN LATERAL unnest (i.indoption) WITH ORDINALITY AS o (option, ordinality)
ON c.ordinality = o.ordinality
JOIN pg_attribute AS a ON trel.oid = a.attrelid AND a.attnum = c.colnum
GROUP BY tnsp.nspname, trel.relname, irel.relname
If you are also interested in index size, you may use this query from the PostgreSQL Wiki.
SELECT
t.tablename,
indexname,
c.reltuples AS num_rows,
pg_size_pretty(pg_relation_size(quote_ident(t.tablename)::text)) AS table_size,
pg_size_pretty(pg_relation_size(quote_ident(indexrelname)::text)) AS index_size,
CASE WHEN indisunique THEN 'Y'
ELSE 'N'
END AS UNIQUE,
idx_scan AS number_of_scans,
idx_tup_read AS tuples_read,
idx_tup_fetch AS tuples_fetched
FROM pg_tables t
LEFT OUTER JOIN pg_class c ON t.tablename=c.relname
LEFT OUTER JOIN
( SELECT c.relname AS ctablename, ipg.relname AS indexname, x.indnatts AS number_of_columns, idx_scan, idx_tup_read, idx_tup_fetch, indexrelname, indisunique FROM pg_index x
JOIN pg_class c ON c.oid = x.indrelid
JOIN pg_class ipg ON ipg.oid = x.indexrelid
JOIN pg_stat_all_indexes psai ON x.indexrelid = psai.indexrelid )
AS foo
ON t.tablename = foo.ctablename
WHERE t.schemaname='public'
ORDER BY 1,2;
For Non-Composite Indexes
select t.relname,i.relname ,
STRING_AGG(pga.attname||'', ','order by i.relname,pga.attnum) as columnName
from pg_class t inner join pg_index ix
on t.oid = ix.indrelid
inner join pg_class i
on i.oid = ix.indexrelid
inner join pg_attribute pga
on
pga.attrelid = i.oid
inner join pg_indexes pgidx
on pgidx.indexname=i.relname
where
t.relkind = 'r'
and pgidx.schemaname='asit_cm'
and t.relname ='accessory'
group by t.relname,i.relname having count(*)=1
For Composite Indexes
select t.relname,i.relname ,
STRING_AGG(pga.attname||'', ','order by i.relname,pga.attnum) as columnName
from pg_class t inner join pg_index ix
on t.oid = ix.indrelid
inner join pg_class i
on i.oid = ix.indexrelid
inner join pg_attribute pga
on
pga.attrelid = i.oid
inner join pg_indexes pgidx
on pgidx.indexname=i.relname
where
t.relkind = 'r'
and pgidx.schemaname='asit_cm'
and t.relname ='accessory'
group by t.relname,i.relname having count(*)=1

How to formulate T-SQL to exclude duplicates?

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
)