Looping through groups of records - sql

SQL Server 2014, I have a table with a number of rows for example 15, 5 have a groupid column of 736881 and 10 have a group id column 3084235. What I want to do is process each group of records in turn and load the results in to a table.
I have written the code to do this but I think I am not setting the loopcounter incorrectly set as I keep getting the groupid of records 736881 loaded twice.
I cant't currently post the test data due to containing personal information but if the mistake is not obvious I will try and create some dummy data.
SELECT #LoopCounter = min(rowfilter) , #maxrowfilter = max(rowfilter)
FROM peops6
WHILE ( #LoopCounter IS NOT NULL
AND #LoopCounter <= #maxrowfilter)
begin
declare #customer_dist as Table (
[id] [int] NOT NULL,
[First_Name] [varchar](50) NULL,
[Last_Name] [varchar](50) NULL,
[DoB] [date] NULL,
[post_code] [varchar](50) NULL,
[mobile] [varchar](50) NULL,
[Email] [varchar](100) NULL );
INSERT INTO #customer_dist (id, First_Name, Last_Name, DoB, post_code, mobile, Email)
select id, first_name, last_name, dob, postcode, mobile_phone, email from peops6 where rowfilter = #LoopCounter
insert into results
SELECT result.* ,
[dbo].GetPercentageOfTwoStringMatching(result.DoB, d.DoB) [DOB%match] ,
[dbo].GetPercentageOfTwoStringMatching(result.post_code, d.post_code) [post_code%match] ,
[dbo].GetPercentageOfTwoStringMatching(result.mobile, d.mobile) [mobile%match] ,
[dbo].GetPercentageOfTwoStringMatching(result.Email, d.Email) [email%match]
FROM ( SELECT ( SELECT MIN(id)
FROM #customer_dist AS sq
WHERE sq.First_Name = cd.First_Name
AND sq.Last_Name = cd.Last_Name
AND ( sq.DoB = cd.DoB
OR sq.mobile = cd.mobile
OR sq.Email = cd.Email
OR sq.post_code = cd.post_code )) nid ,
*
FROM #customer_dist AS cd ) AS result
INNER JOIN #customer_dist d ON result.nid = d.id order by 1, 2 asc;
SELECT #LoopCounter = min(rowfilter) FROM peops6
WHERE rowfilter > #LoopCounter
end

You need to truncate your table variable (#customer_dist) at the end of the loop:
....
-- Add this
TRUNCATE TABLE #customer_dist
SELECT #LoopCounter = min(rowfilter) FROM peops6
WHERE rowfilter > #LoopCounter
end
See: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/42ef20dc-7ad8-44f7-b676-a4596fc0d593/declaring-a-table-variable-inside-a-loop-does-not-delete-the-previous-data?forum=transactsql

I am not sure you need a LOOP like using a SQL Cursor to fulfill this task
Please check following SQL statement where I used multiple CTE expressions
with customer_dist as (
select
rowfilter,
id, first_name, last_name, dob, postcode, mobile_phone, email
from peops6
), result as (
SELECT
(
SELECT
MIN(id)
FROM customer_dist AS sq
WHERE
sq.rowfilter = cd.rowfilter
AND sq.First_Name = cd.First_Name
AND sq.Last_Name = cd.Last_Name
AND (sq.DoB = cd.DoB OR sq.mobile_phone = cd.mobile_phone OR sq.Email = cd.Email OR sq.postcode = cd.postcode )
) nid,
*
FROM customer_dist AS cd
)
SELECT
result.* ,
[dbo].edit_distance(result.DoB, d.DoB) [DOB%match] ,
[dbo].edit_distance(result.postcode, d.postcode) [post_code%match] ,
[dbo].edit_distance(result.mobile_phone, d.mobile_phone) [mobile%match] ,
[dbo].edit_distance(result.Email, d.Email) [email%match]
FROM result
INNER JOIN customer_dist d
ON result.nid = d.id
order by 1, 2 asc;
Please note, I used my fuzzy string matching Levenshtein Distance Algorithm in this sample instead of your function
And the outcome is as follows
Only you need to add the INSERT statement just before the last SELECT statement
Hope it is useful

Related

How to create SQL Server tree in one row?

create table Test
(
Id int identity,
Name varchar(50) not null,
SName varchar(50) null,
ParentId int null
)
insert into Test
values ('aaa', 'bbb', null), ('adf', '22b', null), ('aad', 'bbsd',2),('asdsaa', 'bf', 3),('sdfs','sdf',3),('iopio','uiopio',3)
select * from Test
I have a table with parentid, and I want to get something like that
Name SName "aaa" "bbb" , "adf" {"aad":{"asdsaa":"bf"}}
from the selected values
I have been trying to get it with a recursive query, but...
WITH tree_view AS
(
SELECT
Id, ParentId, Name, SName
FROM
Test
UNION ALL
SELECT
parent.Id, parent.ParentId, parent.Name, parent.SName
FROM
Test parent
JOIN
tree_view tv ON parent.ParentId = tv.Id
)
SELECT DISTINCT *
FROM tree_view
I want to get this
if the parent id is not null, in one sell I want to get Name:SName in Sname field
I think you need to use PIVOT:
Below is similar solution which you can try
Sample Table creation:
CREATE TABLE [dbo].[TestTable](
[Id] [int] NULL,
[Name] [nvarchar](50) NULL,
[Description] [nvarchar](50) NULL)
Inserting sample values:
INSERT INTO TestTable VALUES (1,'Test1a','TestDesc1a')
INSERT INTO TestTable VALUES (2,'Test1b','TestDesc1b')
INSERT INTO TestTable VALUES (3,'Test2a','TestDesc2a')
INSERT INTO TestTable VALUES (4,'Test2b','TestDesc2b')
Query to get the desired output using Pivot:
SELECT 'Name' AS [Column], [1], [2],[3],[4]
FROM
(SELECT Name, id from TestTable) AS ST
PIVOT
(Max(Name) FOR ID IN ([1], [2],[3],[4])) AS PT
UNION
SELECT 'Description' AS [Column], [1], [2],[3],[4]
FROM
(SELECT id,[Description] from TestTable) AS ST
PIVOT
(Max([Description]) FOR ID IN ([1], [2],[3],[4])) AS PT
ORDER BY [Column] DESC
OutPut:
Column 1 2 3 4
Name Test1a Test1b Test2a Test2b
Description TestDesc1a TestDesc1b TestDesc2a TestDesc2b
Hope this helps to solve your question.
If you ar sure any parent leads to only 1 leaf, it's possible to generate the JSON you want by playing only with string manipulation:
with rel_hier(id, parentid, name, sname, js) as (
select m.id, m.parentid, m.name, m.sname,
CAST(CASE WHEN m.parentid IS NULL THEN
CONCAT('"' , m.sname , '"') ELSE
CONCAT('{"' , m.name , '" : "' , m.sname , '"}') END AS VARCHAR(2000))
js
from Test m
where not exists(select 1 from Test t1 where t1.parentid = m.id)
union all
select m.id, m.parentid, m.name, m.sname,
CAST(CASE WHEN m.parentid IS NULL THEN r.js ELSE CONCAT('{"' , m.name ,
'" : ' , r.js , '}') END AS VARCHAR(2000)) js
from rel_hier r
join Test m on m.id = r.parentid
)
SELECT name, js as sname FROM rel_hier r
WHERE parentid IS NULL
;
name sname
aaa "bbb"
adf {"aad" : {"asdsaa" : "bf"}}
But you should also better explain the substitution rules for a number of levels > 3.

SQL Server SELECT first occurrence OR if no occurrence SELECT other criteria

I am having an issue trying to form the proper SQL query for the job here. I have two tables, one is called CUSTOMER and the other is called CUSTOMER_CONTACT. To simplify this, I will only include the relevant column names.
CUSTOMER columns: ID, CUSTOMERNAME
CUSTOMER_CONTACT columns: ID, CUSTOMER_ID, CONTACT_VC, EMAIL
CUSTOMER_ID is the foreign key to link to the CUSTOMER table from CUSTOMER_CONTACT. CONTACT_VC is just the entry number for their contact information. There could be multiple CUSTOMER_CONTACT records for each customer, but they will have a unique CONTACT_VC.
EMAIL can be null/blank on some or all as well.
I need to select the first CUSTOMER_CONTACT entry where EMAIL is NOT NULL/blank but if none of the CUSTOMER_CONTACT entries have an email address, then select CUSTOMER_CONTACT WHERE CONTACT_VC = 1
Any suggestions on how to accomplish this?
The following approach uses ROW_NUMBER to retrieve a number based on your ordering logic within each CUSTOMER_ID group, then filters by the first record retrieved.
You may try the following:
SELECT
*
FROM (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY CUSTOMER_ID
ORDER BY (CASE WHEN EMAIL IS NOT NULL THEN 0 ELSE 1 END),CONTACT_VC
) as rn
FROM
CUSTOMER_CONTACT
) t
WHERE rn=1
If you would like to join this to the customer table you may use the above query as a subquery eg
SELECT
c.*,
contact.*
FROM
CUSTOMER c
INNER JOIN (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY CUSTOMER_ID
ORDER BY (CASE WHEN EMAIL IS NOT NULL THEN 0 ELSE 1 END),CONTACT_VC
) as rn
FROM
CUSTOMER_CONTACT
) contact ON c.ID = contact.CUSTOMER_ID and contact.rn=1
Here is almost the same answer as ggordon, but I used a common table expression and I think the ordering in the subquery portion should go by CONTACT_VS first then by non-NULL email addresses. I created some very simple test data to run this:
DECLARE #CUSTOMER AS TABLE
(
[ID] INT NOT NULL,
[CUSTOMERNAME] VARCHAR(10) NOT NULL
);
INSERT INTO #CUSTOMER
(
[ID],
[CUSTOMERNAME]
)
VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Cathy');
DECLARE #CUSTOMER_CONTACT AS TABLE
(
[ID] INT NOT NULL,
[CUSTOMER_ID] INT NOT NULL,
[CONTACT_VC] INT NOT NULL,
[EMAIL] VARCHAR(40) NULL
);
INSERT INTO #CUSTOMER_CONTACT
(
[ID],
[CUSTOMER_ID],
[CONTACT_VC],
[EMAIL]
)
VALUES
(1, 1, 1, 'alice#email.com'),
(2, 1, 2, 'alice#gmail.com'),
(3, 2, 1, NULL),
(4, 2, 2, 'bob#work.com'),
(5, 3, 1, NULL),
(6, 3, 2, NULL),
(7, 3, 3, NULL);
;WITH [cc]
AS (SELECT [ID],
[CUSTOMER_ID],
[CONTACT_VC],
[EMAIL],
ROW_NUMBER() OVER (PARTITION BY [CUSTOMER_ID]
ORDER BY [CONTACT_VC],
(CASE WHEN [EMAIL] IS NOT NULL THEN
0
ELSE
1
END
)
) AS [rn]
FROM #CUSTOMER_CONTACT)
SELECT [c].[ID], [c].[CUSTOMERNAME], [cc].[ID], [cc].[CUSTOMER_ID], [cc].[CONTACT_VC], [cc].[EMAIL]
FROM #CUSTOMER AS [c]
INNER JOIN [cc]
ON [c].[ID] = [cc].[CUSTOMER_ID]
AND [cc].[rn] = 1;
select * from CUSTOMER_CONTACT where EMAIL IS NOT NULL
union all
select * from CUSTOMER_CONTACT where
(CONTACT_VC=1 and NOT EXISTS (select 1 FROM CUSTOMER_CONTACT where EMAIL IS NOT NUL)
order by CONTACT_VC asc limit 1

SQL Server SQL Statement - Updating record

I have a data as below:
I need to update Matching_id and Matching_Type by using column id, region, company, dept, subdept and amountsepend. The logic is:
Sum AmountSepend by Region, Company, Dept and SubDept. If the sum amount is 0 then Matching_Type is 'Match' and Matching_id is the combination of the id for the matched record else 'Not Match' and Matching_id is the id. **SUM means the total sum of all records for same criteria regardless the AmountSepend is positive or negative.
Another important criteria is if the transaction is single record, meaning the total count by grouping by Region, Company, Dept and SubDept is 1 then Matching type is Not Match and Matching_UID is id regardless the AmountSepend is 0 or positive/negative value. Example id 8.
Below is the output:
Here the table and data script
CREATE TABLE [dbo].[StackoverflowQuest](
[id] [int] NOT NULL,
[Region] [varchar](50) NULL,
[Company] [varchar](50) NULL,
[Dept] [varchar](50) NULL,
[SubDept] [varchar](50) NULL,
[AmountSepend] [float] NULL,
[Matching_id] [varchar](100) NULL,
[Matching_Type] [varchar](100) NULL
) ON [PRIMARY]
How could I achieved such result ? Any help/hint would be appreciate
CREATE TABLE #Table(Id INT,Region VARCHAR(100),Company INT,Dept INT,SubDept
INT,AmtSpend INT,MatchingId VARCHAR(100),MatchingType VARCHAR(100))
INSERT INTO #Table(Id ,Region ,Company , Dept ,SubDept ,AmtSpend )
SELECT 1,'NAM',12378,1,NULL,900 UNION ALL
SELECT 2,'NAM',12378,1,NULL,-900 UNION ALL
SELECT 3,'NAM',12370,1,23,1000 UNION ALL
SELECT 4,'ASA',1234,9,12,5000 UNION ALL
SELECT 5,'NAM',12370,1,23,-1000 UNION ALL
SELECT 6,'ASA',1234,9,12,800 UNION ALL
SELECT 7,'ASA',1234,9,12,-600 UNION ALL
SELECT 8,'ASA',12311,6,NULL,200
UPDATE #Table SET MatchingId = MatchIds,MatchingType = 'Match'
FROM
(
SELECT T2.Company,STUFF( ( SELECT ',' + CAST(T3.Id AS VARCHAR) FROM #Table
T3 WHERE T2.Company = T3.Company FOR XML PATH('')),1,1,'') MatchIds
FROM #Table T2
JOIN
(
SELECT T1.Company Company,SUM(T1.AmtSpend) Total
FROM #Table T1
GROUP BY T1.Company
HAVING SUM(T1.AmtSpend) = 0
)A ON A.Company = T2.Company
GROUP BY T2.Company
) A
WHERE A.Company = #Table.Company
UPDATE #Table SET MatchingId = CAST(Id AS VARCHAR),MatchingType = 'Not
Match' WHERE ISNULL(MatchingId,'') = ''
SELECT * FROM #Table

Remove duplicates with less null values

I have a table of employees which contains about 25 columns. Right now there are a lot of duplicates and I would like to try and get rid of some of these duplicates.
First, I want to find the duplicates by looking for multiple records that have the same values in first name, last name, employee number, company number and status.
SELECT
firstname,lastname,employeenumber, companynumber, statusflag
FROM
employeemaster
GROUP BY
firstname,lastname,employeenumber,companynumber, statusflag
HAVING
(COUNT(*) > 1)
This gives me duplicates but my goal is to find and keep the best single record and delete the other records. The "best single record" is defined by the record with the least amount of NULL values in all of the other columns. How can I do this?
I am using Microsoft SQL Server 2012 MGMT Studio.
EXAMPLE:
Red: DELETE
Green: KEEP
NOTE: There are a lot more columns in the table than what this table shows.
You can use the sys.columns table to get a list of columns and build a dynamic query. This query will return a 'KeepThese' value for every record you want to keep based on your given criteria.
-- insert test data
create table EmployeeMaster
(
Record int identity(1,1),
FirstName varchar(50),
LastName varchar(50),
EmployeeNumber int,
CompanyNumber int,
StatusFlag int,
UserName varchar(50),
Branch varchar(50)
);
insert into EmployeeMaster
(
FirstName,
LastName,
EmployeeNumber,
CompanyNumber,
StatusFlag,
UserName,
Branch
)
values
('Jake','Jones',1234,1,1,'JJONES','PHX'),
('Jake','Jones',1234,1,1,NULL,'PHX'),
('Jake','Jones',1234,1,1,NULL,NULL),
('Jane','Jones',5678,1,1,'JJONES2',NULL);
-- get records with most non-null values with dynamic sys.column query
declare #sql varchar(max)
select #sql = '
select e.*,
row_number() over(partition by
e.FirstName,
e.LastName,
e.EmployeeNumber,
e.CompanyNumber,
e.StatusFlag
order by n.NonNullCnt desc) as KeepThese
from EmployeeMaster e
cross apply (select count(n.value) as NonNullCnt from (select ' +
replace((
select 'cast(' + c.name + ' as varchar(50)) as value union all select '
from sys.columns c
where c.object_id = t.object_id
for xml path('')
) + '#',' union all select #','') + ')n)n'
from sys.tables t
where t.name = 'EmployeeMaster'
exec(#sql)
Try this.
;WITH cte
AS (SELECT Row_number()
OVER(
partition BY firstname, lastname, employeenumber, companynumber, statusflag
ORDER BY (SELECT NULL)) rn,
firstname,
lastname,
employeenumber,
companynumber,
statusflag,
username,
branch
FROM employeemaster),
cte1
AS (SELECT a.firstname,
a.lastname,
a.employeenumber,
a.companynumber,
a.statusflag,
Row_number()
OVER(
partition BY a.firstname, a.lastname, a.employeenumber, a.companynumber, a.statusflag
ORDER BY (CASE WHEN a.username IS NULL THEN 1 ELSE 0 END +CASE WHEN a.branch IS NULL THEN 1 ELSE 0 END) )rn
-- add the remaining columns in case statement
FROM cte a
JOIN employeemaster b
ON a.firstname = b.firstname
AND a.lastname = b.lastname
AND a.employeenumber = b.employeenumber
AND a.companynumbe = b.companynumber
AND a.statusflag = b.statusflag)
SELECT *
FROM cte1
WHERE rn = 1
I test with MySQL and use NULL String concat to found the best record. Because LENGTH ( NULL || 'data') is 0. Only if all column not NULL some length exists. Maybe this is not perfekt.
create table EmployeeMaster
(
Record int auto_increment,
FirstName varchar(50),
LastName varchar(50),
EmployeeNumber int,
CompanyNumber int,
StatusFlag int,
UserName varchar(50),
Branch varchar(50),
PRIMARY KEY(record)
);
INSERT INTO EmployeeMaster
(
FirstName, LastName, EmployeeNumber, CompanyNumber, StatusFlag, UserName, Branch
) VALUES ('Jake', 'Jones', 1234, 1, 1, 'JJONES', 'PHX'), ('Jake', 'Jones', 1234, 1, 1, NULL, 'PHX'), ('Jake', 'Jones', 1234, 1, 1, NULL, NULL), ('Jane', 'Jones', 5678, 1, 1, 'JJONES2', NULL);
My query idea looks like this
SELECT e.*
FROM employeemaster e
JOIN ( SELECT firstname,
lastname,
employeenumber,
companynumber,
statusflag,
MAX( LENGTH ( username || branch ) ) data_quality
FROM employeemaster
GROUP BY firstname, lastname, employeenumber, companynumber, statusflag
HAVING count(*) > 1
) g
ON LENGTH ( username || branch ) = g.data_quality

Why does my insert for new records only does not work even if I'm using where not exits to a subquery?

This is the script I used to create the table.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ODSCustomerBase]') AND type in (N'U'))
DROP TABLE [ODSCustomerBase]
Go
Create Table ODSCustomerBase
(CustomerBaseID int NOT NULL identity primary key,
RecordSource nvarchar(4),
RecordType varchar(2),
SiteURN nvarchar(128)NOT NULL,
SiteDesc nvarchar(60)NULL,
CustomerLink nvarchar(120)NOT NULL,
HomeCurrencyCode nvarchar(8)NOT NULL,
CustomerID nvarchar(15)NOT NULL,
CustomerCurrencyCode nvarchar(8)NOT NULL,
CustomerName nvarchar(120)NULL,
CustomerShortName nvarchar(30) NOT NULL,
Address nvarchar(255)NULL,
City nvarchar(25)NULL,
PostalCode nvarchar(10) NULL,
CountryCode nvarchar(3) NOT NULL,
CountryName nvarchar(60) NOT NULL,
StateCode nvarchar(8) NULL,
StateName nvarchar(60) NULL,
Phone nvarchar(30) NOT NULL,
Fax nvarchar(30) NULL,
TaxCode nvarchar(15) NULL,
ProspectID nvarchar(15) NULL,
CreateDate datetime NOT NULL,
LastUpdateDate datetime NULL)
This is the script I used to insert records for the first time
insert into SEC_ODS.dbo.ODSCustomerBase
select
--Identity as CustomerBaseID
'E4SE' as Recordsource, --could be others, eg 'BST', CRM, nvarchar(4)'
'C' as RecordType, --could be 'p'as prospects, add a case statement
ss.siteURN,
ss.sitedesc,
ss.FS_URL + 'frmcustomer.aspx?CustomerID=' + customerid as CustomerLink,
co.HomeCurrencyCode,
c.customerid,
c.currencycode as customercurrencycode,
c.entityname as CustomerName,
c.entityshortname CustomerShortName,
c.address,
c.city,
c.postalcode,
c.countrycode,
cn.countryname,
c.statecode,
s.statename,
c.phone,
c.fax,
c.taxcode,
c.prospectid,
c.createdate,
c.lastupdatedate
from country cn,
SECSite ss,
company co,
customer c
left outer join state s
on c.statecode = s.statecode
where ss.LocalSiteFlag = 1
and cn.countrycode = c.countrycode
So if I check the ODS table using this script, it gives me 4395 results
use sec_ods
go
select count(*) from ODSCustomerBase
While this is the script that I use to insert NEW RECORDS ONLY. This is where I used the where not exist condition and the sub query which doesn't work because it doubles the number of records. The goal is to insert only new records.
insert into SEC_ODS.dbo.ODSCustomerBase
select
--Identity as CustomerBaseID
'E4SE' as Recordsource, --could be others, eg 'BST', CRM, nvarchar(4)'
'C' as RecordType, --could be 'p'as prospects, add a case statement
ss.siteURN,
ss.sitedesc,
ss.FS_URL + 'frmcustomer.aspx?CustomerID=' + customerid as CustomerLink,
co.HomeCurrencyCode,
c.customerid,
c.currencycode,
c.entityname,
c.entityshortname,
c.address,
c.city,
c.postalcode,
c.countrycode,
cn.countryname,
c.statecode,
s.statename,
c.phone,
c.fax,
c.taxcode,
c.prospectid,
c.createdate,
c.lastupdatedate
from country cn,
SECSite ss,
company co,
customer c
left outer join state s
on c.statecode = s.statecode
where ss.LocalSiteFlag = 1
and cn.countrycode = c.countrycode
and not exists(select * from SEC_ODS.dbo.ODSCustomerBase b
where(Recordsource=b.Recordsource and
RecordType=b.RecordType and
ss.siteURN=b.siteURN and
ss.sitedesc=b.sitedesc and
ss.FS_URL=b.CustomerLink and
co.HomeCurrencyCode=b.HomeCurrencyCode and
c.customerid=b.customerid and
c.currencycode=b.CustomerCurrencyCode and
c.entityname=b.CustomerName and
c.entityshortname=b.CustomerShortName and
c.address=b.address and
c.city=b.city and
c.postalcode=b.postalcode and
c.countrycode=b.countrycode and
cn.countryname=b.countryname and
c.statecode=b.statecode and
s.statename=b.statename and
c.phone=b.phone and
c.fax=b.fax and
c.taxcode=b.taxcode and
c.prospectid=b.prospectid and
c.createdate=b.createdate and
c.lastupdatedate=b.lastupdatedate))
So if I check the ODS table using this script, it gives me 8790 results which is wrong.
use sec_ods
go
select count(*) from ODSCustomerBase
Can someone help me with this please?
Thank you.
Use either ISNULL or COALESCE around all the fields that could be NULL.
e.g. ISNULL(c.address,'') = ISNULL(b.address,'')
If you want to restrict the already inserted data better to go Merge Statment it will just update the existing data or insert the new data
MERGE ODSCustomerBase AS T
USING (
SELECT Col1,col2,.... FROM ODSCustomerBase
) AS S
ON (
t.Col1 = s.Col1
AND t.Col2 = s.Col2
AND .....
)
WHEN NOT MATCHED BY TARGET
THEN
INSERT (
Col1
,Col2
,....
,....
)
VALUES (
S.Col1
--,S.NrID
,s.Col2
,s.Col3
)
WHEN MATCHED
THEN
UPDATE
SET T.Col1 = S.Col1
WHEN NOT MATCHED BY SOURCE
AND EXISTS (
SELECT 1
FROM ODSCustomerBase c
WHERE t.Col1 = Col1
)
THEN
DELETE;