Unable to get the required result using update statement - sql

I am unable to update the data using record by record below scenario.
Required output: patient will able to Admit/Re-admit multiple times in hospital, if a patient readmitted multiple times in hospital after the first visit, first visit record will get Re-admission=0 and Index=1. This visit should cal Index_Admission of that patient. using this index_admission should calculate the 30-day readmission.
Current Output:
Calculation:
From index_admission discharge date to next admit_visit date,
1) if the diff is having less than 30 days, readmission=1 and Index=0
else readmission=0 and Index=1 should be update.
For checking this every time should check using the latest index_admission discharge_date.
To get this result i written below logic, but it's updating readmission=0 and Index=1 after 30-day post discharge of using first index admission.
UPDATE Readmission
SET Index_AMI = (CASE
WHEN DATEDIFF(DD, (SELECT
Sub.Max_Index_Dis
FROM (SELECT
Patient_ID,
MAX(Discharge_Date_Time) Max_Index_Dis
FROM Readmission
WHERE Index_AMI = 1 AND FPR.Patient_ID = Patient_ID
GROUP BY Patient_ID) Sub), FPR.Admit_Date_Time) <= 31 THEN 0 ELSE 1
END),
Is_AMI_Readmission = (CASE
WHEN DATEDIFF(DD, (SELECT
Sub.Max_Index_Dis
FROM (SELECT
Patient_ID,
MAX(Discharge_Date_Time) Max_Index_Dis
FROM Readmission
WHERE Index_AMI = 1 AND FPR.Patient_ID = Patient_ID
GROUP BY Patient_ID) Sub)
, FPR.Admit_Date_Time) <= 31 THEN 1 ELSE 0
END)
FROM Readmission FPR
WHERE fpr.index_ami IS NULL
Expected Result:
Please help me to resolve the issue.
Best Regards,
Nagendra

Thank you all for trying to help.
I some how managed to solve it using temporary tables.
If there is any issues, especially performance, with this approach please feel free to comment/criticize.
/*------------ To moving all Patient_Readmission data into temp table -------------*/
IF EXISTS (select * FROM tempdb.dbo.sysobjects o
WHERE o.xtype IN ('U')
AND o.id = OBJECT_ID(N'tempdb..#Readmission')
)
Begin
DROP TABLE #Readmission
End
IF NOT EXISTS (SELECT * FROM tempdb.dbo.sysobjects o
WHERE o.xtype IN ('U')
AND o.id = OBJECT_ID(N'tempdb..#Readmission')
)
BEGIN
select Patient_ID,ID,Encounter_Code
,Admit_Date_Time,Discharge_Date_Time
,Is_AMI_Readmission,Index_AMI
into #Readmission
from Patient_Readmission
END
GO
/*----------- To get Max Index discharge_date for all patients where index=1----------*/
IF EXISTS (select * FROM tempdb.dbo.sysobjects o
WHERE o.xtype IN ('U')
AND o.id = OBJECT_ID(N'tempdb..#Each_Pt_Max_Dsrg')
)
Begin
DROP TABLE #Each_Pt_Max_Dsrg
End
IF NOT EXISTS (SELECT * FROM tempdb.dbo.sysobjects o
WHERE o.xtype IN ('U')
AND o.id = OBJECT_ID(N'tempdb..#Each_Pt_Max_Dsrg')
)
BEGIN
select Patient_ID,Index_AMI,Max(Discharge_Date_Time) Max_Index_Dis
into #Each_Pt_Max_Dsrg
from #Readmission where Index_AMI=1 group by Patient_ID,Index_AMI
END
Declare #var int
Set #var=(select Min(Patient_ID) from #Each_Pt_Max_Dsrg)
While #var is not null
Begin
Declare #Var_En int
declare #maxDisch datetime
Set #Var_En=(Select Min(ID) From #Readmission Where Index_AMI Is null and Patient_ID=#var)
While #Var_En is Not NULL
Begin
set #maxDisch = dateadd(dd,-1,(select max(Max_Index_Dis) from #Each_Pt_Max_Dsrg where Index_AMI=1 and Patient_ID=#var))
while (#maxDisch < (select max(Max_Index_Dis) from #Each_Pt_Max_Dsrg where Index_AMI=1 and Patient_ID=#var))
begin
Update #Readmission
set Index_AMI=(Case When Datediff(DD,(Select Max(Max_Index_Dis) From #Each_Pt_Max_Dsrg Where Index_AMI=1 And Patient_ID=#var),FPR.Admit_Date_Time) between 0 and 31 Then 0 Else 1 End)
,Is_AMI_Readmission=(Case When Datediff(DD,(Select Max(Max_Index_Dis) From #Each_Pt_Max_Dsrg Where Index_AMI=1 And Patient_ID=#var),FPR.Admit_Date_Time) between 0 and 31 Then 1 Else 0 End)
From #Readmission FPR where Patient_ID=#var and ID=#Var_En and Index_AMI is NULL
set #maxDisch = (select max(Max_Index_Dis) from #Each_Pt_Max_Dsrg where Index_AMI=1 and Patient_ID=#var)
delete from #Each_Pt_Max_Dsrg
insert into #Each_Pt_Max_Dsrg
select Patient_ID,Index_AMI,Max(Discharge_Date_Time) Max_Index_Dis
from #Readmission where Index_AMI=1 group by Patient_ID,Index_AMI
end
SET #Var_En = (SELECT Min(ID) FROM #Readmission WHERE ID> #Var_En)
End
SET #Var = (SELECT MIN(Patient_ID) FROM #Each_Pt_Max_Dsrg WHERE Patient_ID > #var)
End

Related

Used Cursor inside cursor for update it is showing o rows effected, logic is working when i tried manually

stored procedure
Used Cursor inside cursor for update it is showing 0 rows effected, logic is working when i tried manually, declaring and closing done properly.
any changes do i need to do
or any alternatives than cursor.
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
ALTER PROCEDURE [dbo].[POS_Discount_Report]
#OutletId INT = NULL,
#FromDate DATE = NULL,
#ToDate DATE = NULL,
#DiscountPercent DECIMAL = NULL
AS
begin
SELECT #CutOffInvoiceAmount = AVG(InvoiceAmount) FROM POS_SalesReceiptMaster WHERE StampDate BETWEEN #FromDate AND #ToDate
DECLARE Receipt_cursor CURSOR FOR
SELECT Id FROM POS_SalesReceiptMaster WHERE StampDate BETWEEN #FromDate AND #ToDate AND InvoiceAmount <= #CutOffInvoiceAmount
OPEN Receipt_cursor
FETCH NEXT FROM Receipt_cursor
INTO #ReceiptId
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE Item_cursor CURSOR FOR
SELECT Id FROM Updated_SalesReceiptItems WHERE ReceiptId = #ReceiptId
OPEN Item_cursor
FETCH NEXT FROM Item_cursor
INTO #ID
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #Percentage = Percentage, #ItemPrice = Price FROM
Updated_SalesReceiptItems WHERE Id = #ID
IF #Percentage = 5
BEGIN
SELECT #UpdatePercentage = Tax5 FROM Updated_Master
Where Percentage = #DiscountPercent
END
ELSE
BEGIN
#UpdatePercentage = 5
END
UPDATE Updated_SalesReceiptItems
SET ProductId = Product.ProductId,
Actualprice = Product.Actualprice,
Quantity = Product.Qty,
ProductName = Product.ProductName,
unit = Product.unit,
CategoryName= Product.CategoryName,
Percentage= Product.Percentage,
Amount = Product.Amount FROM
(SELECT TOP 1 PM.ProductId, ProductCode,
dbo.fn_Get_ProductPrice_By_Outlet(ProductId,#OutletId)
AS
Actualprice,
(CASE WHEN ( dbo.fn_Get_ProductPrice_By_Outlet(#OutletId, ProductId) != 0)
THEN (#ItemPrice / dbo.fn_Get_ProductPrice_By_Outlet(#OutletId, ProductId))
ELSE 0
END) AS Qty,
ProductName, Unit, CategoryName, #UpdatePercentage AS Percentage,
dbo.fn_Get_ProductPrice_By_Outlet(#OutletId, ProductId) * (#UpdatePercentage/100) AS TaxAmount
FROM dbo.Products_Master PM
INNER JOIN ProductCategory_Master CM ON PM.CategoryId = CM.CategoryId
INNER JOIN tax_master TM ON PM.TaxId = TM.Id
WHERE (#ItemPrice) % nullif(dbo.fn_Get_ProductPrice_By_Outlet(#OutletId, ProductId),0) = 0
AND Percentage = #UpdatePercentage) Product
WHERE Id = #ID
end
FETCH NEXT FROM Item_cursor
INTO #ID
END
CLOSE Item_cursor;
DEALLOCATE Item_cursor;
FETCH NEXT FROM Receipt_cursor
INTO #ReceiptId
END
CLOSE Receipt_cursor;
DEALLOCATE Receipt_cursor;
END
Okay, this is pretty scrappy, and probably won't work without some fixing, but it should give you the general pattern for doing all of this in a single query?
ALTER PROCEDURE POS_Discount_Report (
#OutletId INT = NULL,
#FromDate DATE = NULL,
#ToDate DATE = NULL,
#DiscountPercent DECIMAL = NULL)
AS
BEGIN
DECLARE #CutOffInvoiceAmount NUMERIC(19,2); --?? seems to be missing from original procedure
SELECT #CutOffInvoiceAmount = AVG(InvoiceAmount) FROM POS_SalesReceiptMaster WHERE StampDate BETWEEN #FromDate AND #ToDate; --What happens if one or both of these is NULL?
--CTEs
WITH Receipt AS (
SELECT Id FROM POS_SalesReceiptMaster WHERE StampDate BETWEEN #FromDate AND #ToDate AND InvoiceAmount <= #CutOffInvoiceAmount),
Item AS (
SELECT Id FROM Updated_SalesReceiptItems s INNER JOIN Receipt r ON s.ReceiptId = r.Id),
PercentQuery AS (
SELECT i.Id, u.[Percentage], u.Price FROM Updated_SalesReceiptItems u INNER JOIN Item i ON u.Id = i.Id),
UpdatePercent AS (
SELECT p.Id, p.[Percentage], p.Price, CASE WHEN p.[Percentage] = 5 THEN u.Tax5 ELSE 5 END AS UpdatePercentage FROM PercentQuery p INNER JOIN Updated_Master u ON u.[Percentage] = #DiscountPercent)
UPDATE
u
SET
ProductId = pm.ProductId,
Actualprice = dbo.fn_Get_ProductPrice_By_Outlet(ProductId, #OutletId),
Quantity =
CASE
WHEN (dbo.fn_Get_ProductPrice_By_Outlet(#OutletId, ProductId) != 0)
THEN (#ItemPrice / dbo.fn_Get_ProductPrice_By_Outlet(#OutletId, ProductId))
ELSE 0
END,
ProductName = pm.ProductName,
unit = pm.unit, --not sure on the alias here, as it's missing in the original query
CategoryName = pm.CategoryName,
[Percentage] = u.UpdatePercentage,
Amount = dbo.fn_Get_ProductPrice_By_Outlet(#OutletId, ProductId) * (u.UpdatePercentage / 100) --although this was TaxAmount originally??!
FROM
dbo.Products_Master pm
INNER JOIN ProductCategory_Master cm ON cm.CategoryId = pm.CategoryId
INNER JOIN tax_master tm ON tm.Id = pm.TaxId
INNER JOIN UpdatePercent up ON up.Id = pm.Id
INNER JOIN Updated_SalesReceiptItems u ON u.Id = up.Id
WHERE
(p.Price) % NULLIF(dbo.fn_Get_ProductPrice_By_Outlet(#OutletId, pm.ProductId), 0) = 0
AND [Percentage] = UpdatePercentage;
END;
Basically, I use nested common-table expressions to perform the same action as your original cursors, but these are now set-based. This means I can JOIN the results to the table to be updated and perform all of the updates in a single hit.
I almost certainly got some of this wrong, as I could see a number of parts in your original query that just seemed incorrect?

Using IF without an ELSE condition in SQL

I'm trying to use the below query to update some data only if #rowcount is greater than 0. However, its executing the update statement even when #RowCount is 0. Can someone help whats wrong in here please? I would like to do nothing if #RowCount is 0.
I'm using SQL Server 2014.
TRUNCATE TABLE Count1
DECLARE #RowCount AS INT
--insert data in a temporary table
SELECT YEAR, S_ID
into #Count1 FROM
(SELECT DISTINCT D.YEAR, S_ID FROM SALES S JOIN TRANSACTIONS PT
ON S.COMBINED_TXN_ID = PT.S_ID AND PT.TRANSACTION_TYPE = 'BILLING'
JOIN DATE D ON D.DAY = S.DAY AND PT.DAY = S.DAY
WHERE
S.SALES_CUSTOMER != PT.CUSTOMER)Counter1;
--Store the rowcount in a temporary variable
SET #RowCount = (SELECT Count(*) FROM #Count1)
--Fix the data with differences only if count>0
IF ##ROWCOUNT > 0
BEGIN
UPDATE SALES
SET SALES_CUSTOMER = PT.CUSTOMER
FROM SALES S
JOIN TRANSACTIONS PT ON S.COMBINED_TXN_ID = PT.S_ID
JOIN DATE D ON D.DAY = S.DAY AND PT.DAY = S.DAY
WHERE
S_ID IN (SELECT S_ID FROM #Count1)
END;
##ROWCOUNT Returns the number of rows affected by the last statement.
Change system variable ##ROWCOUNT by your own variable #RowCount
--Store the rowcount in a temporary variable
SET #RowCount = (SELECT Count(*) FROM #Count1)
--Fix the data with differences only if count>0
IF #RowCount > 0
You are confusing the local variable #RowCount you defined yourself, with the global variable ##ROWCOUNT Microsoft defined for you (which you can't set).
So simply refer to the correct variable. Better yet: rename your local variable to avoid such confusion.
You don't even need the if at all, since the update wouldn't be executed if #Count1 is empty as there are no records to fulfill the where clause (WHERE S_ID IN ({empty result set})).
If you wish to use the same variable you have declared use #rowcount
DECLARE #recordCount INT
--insert data in a temporary table
SELECT YEAR
,S_ID
INTO #Count1
FROM (
SELECT DISTINCT D.YEAR
,S_ID
FROM SALES S
INNER JOIN TRANSACTIONS PT
ON S.COMBINED_TXN_ID = PT.S_ID
AND PT.TRANSACTION_TYPE = 'BILLING'
INNER JOIN DATE D
ON D.DAY = S.DAY
AND PT.DAY = S.DAY
WHERE S.SALES_CUSTOMER != PT.CUSTOMER
) Counter1;
--Store the rowcount in a temporary variable
SELECT #recordCount = count(*)
FROM #Count1
--Fix the data with differences only if count>0
IF (#recordCount > 0)
BEGIN
UPDATE SALES
SET SALES_CUSTOMER = PT.CUSTOMER
FROM SALES S
INNER JOIN TRANSACTIONS PT
ON S.COMBINED_TXN_ID = PT.S_ID
INNER JOIN DATE D
ON D.DAY = S.DAY
AND PT.DAY = S.DAY
WHERE S_ID IN (
SELECT S_ID
FROM #Count1
)
END
You could skip all the temp tables and checks and just do an update. Something like this should be the same thing as all the code you posted.
UPDATE S
SET SALES_CUSTOMER = PT.CUSTOMER
FROM SALES S
JOIN S PT ON S.COMBINED_TXN_ID = PT.S_ID
AND PT.TRANSACTION_TYPE = 'BILLING'
JOIN DATE D ON D.DAY = S.DAY
AND PT.DAY = S.DAY
WHERE S.SALES_CUSTOMER != PT.CUSTOMER

SQL How to count all remains for each date

I have the following SQL function
CREATE FUNCTION [dbo].[GetCardDepartRemains]
(
#CardId INT,
#DepartId INT,
#Date DATETIME = NULL,
#DocumentId INT = NULL
)
RETURNS INT
AS
BEGIN
DECLARE #Res INT
SELECT
#Res = ISNULL(SUM(CASE WHEN Operations.[Output] = 0 AND Operations.RecipientId = #DepartId THEN 1 ELSE -1 END), 0)
FROM dbo.Operations
WHERE Operations.CardId = #CardId
AND (Operations.[Output] = 0 AND Operations.RecipientId = #DepartId OR Operations.Input = 0 AND Operations.SenderId = #DepartId)
AND (#Date IS NULL OR Operations.[Date] <= #Date)
RETURN #Res
END
GO
It counts remains for certain product on certain department on certain date.
If it is less then zero it means something's wrong with database
Now I need to find all remains for each card, for each department for all dates in database where result is wrong.
Theoretically speaking we can fing this by calling this procedure in a query like this
SELECT DISTINCT Operations.[Date] as [Date],
Departments.Id as Depart,
Cards.Id as [Card],
[dbo].[GetCardDepartRemains] (Cards.Id, Departments.Id,Operations.[Date],NULL) as Res
FROM [jewellery].[dbo].[Cards]
CROSS JOIN [jewellery].[dbo].[Departments]
CROSS JOIN [jewellery].[dbo].[Operations]
WHERE [dbo].[GetCardDepartRemains] (Cards.Id, Departments.Id,Operations.[Date],NULL) = -1
But this query executes more than 2 minutes, so we need to write a new query.
My query can find all remains for each card on each department on certain date (ex. '2016-10-04')
SELECT
[Card],
Depart,
Res
FROM
(SELECT
Cards.Id as [Card],
Departments.Id as Depart,
ISNULL(SUM(CASE WHEN Operations.[Output] = 0 AND Operations.RecipientId = Departments.Id THEN 1 ELSE -1 END), 0) as Res
FROM Operations
CROSS JOIN Cards
CROSS JOIN Departments
WHERE Operations.CardId = Cards.Id
AND (Operations.[Output] = 0 AND Operations.RecipientId = Departments.Id OR Operations.Input = 0 AND Operations.SenderId = Departments.Id)
AND (Operations.[Date] <= '2016-10-04')
GROUP BY Cards.Id, Departments.Id
) as X
WHERE Res = -1
Can you help to re-write this query to find remains for all dates?
Assuming SQL Server is 2008 or above:
To find all dates, just comment out the date filter like this:
-- AND (Operations.[Date] <= '2016-10-04')
If you need to filter on a date range:
AND (Operations.[Date] between between getDate()-30 and getDate()
Changing -30 to however many days in the past. So a year ago would be -364.

Less expensive query?

I have a stored procedure that returns an integer 1 or 0 depending on specific criteria. It currently uses three select statements and it will be used heavily by multiple users across multiple locations. There has to be a more efficient way of doing this.
In short the query checks first to see if all checklist items on an order are completed (a separate table), then it checks to see if a field named BreakOutGuest (a bit field) is a 1 or 0. Depending on that result it checks to see if the total guest count is greater than 0 and the order total is zero. It returns the one or zero on all this criteria. Is there a more efficient way to do this? A temp table so I only have to hit the actual tables once? Below is the code.
#ORDERID INT
AS
BEGIN
DECLARE #AUTO_CLOSE INT
SET NOCOUNT ON;
--If all checklist items are marked complete move on, if not set #AUTO_CLOSE=0
IF NOT EXISTS(SELECT ORDERID FROM dbo.orderchecklistitems WHERE OrderID=#ORDERID AND CompletedON IS NULL)
BEGIN
--if BreakOutGuestFees is 1 only sum Guest_Count_1 + Guest_Count_2
IF EXISTS(SELECT * FROM dbo.Orders WHERE (GuestCount_1 + GuestCount_2)>1 AND OrderTotal=0 AND BreakoutGuestFees=1)
BEGIN
SET #AUTO_CLOSE=1
END
ELSE
SET #AUTO_CLOSE=0
--if BreakOutGuestFees is 0 only consider Guest_Count_1
IF EXISTS(SELECT * FROM dbo.Orders WHERE (GuestCount_1)>1 AND OrderTotal=0 AND BreakoutGuestFees=0)
BEGIN
SET #AUTO_CLOSE=1
END
ELSE
SET #AUTO_CLOSE=0
END
ELSE
SET #AUTO_CLOSE=0
END
If am not wrong you can combine two if clause into single if clause by using AND , OR logic. Try this.
IF NOT EXISTS(SELECT ORDERID
FROM dbo.orderchecklistitems
WHERE OrderID = #ORDERID
AND CompletedON IS NULL)
BEGIN
IF EXISTS(SELECT *
FROM dbo.Orders
WHERE ( ( GuestCount_1 + GuestCount_2 > 1
AND BreakoutGuestFees = 1 )
OR ( BreakoutGuestFees = 0
AND GuestCount_1 > 1 ) )
AND OrderTotal = 0
AND OrderID = #ORDERID)
SET #AUTO_CLOSE=1
ELSE
SET #AUTO_CLOSE=0
END
ELSE
SET #AUTO_CLOSE=0
You can perform your selection check with only one query
SELECT
(SELECT sum(1) FROM dual WHERE EXISTS (SELECT ORDERID FROM dbo.orderchecklistitems WHERE OrderID=#ORDERID AND CompletedON IS NULL)),
(SELECT sum(1) FROM dual WHERE EXISTS (SELECT 1 FROM dbo.Orders WHERE (GuestCount_1 + GuestCount_2)>1 AND OrderTotal=0 AND BreakoutGuestFees=1)),
(SELECT sum(1) FROM dual WHERE EXISTS (SELECT 1 FROM dbo.Orders WHERE (GuestCount_1)>1 AND OrderTotal=0 AND BreakoutGuestFees=0))
INTO
result1, result2, result3
from dual
then check results
DELCARE #AUTO_CLOSE INT = 0
IF NOT EXISTS(SELECT ORDERID
FROM dbo.orderchecklistitems
WHERE OrderID = #ORDERID
AND CompletedON IS NULL)
BEGIN
SET #AUTO_CLOSE =
(
SELECT
CASE
WHEN (GuestCount_1 + GuestCount_2 > 1) AND BreakoutGuestFees = 0 THEN 1
WHEN (GuestCount_1 > 1 ) AND BreakoutGuestFees = 1 THEN 1
ELSE 0 END
FROM dbo.orders
WHERE OrderTotal = 0 AND OrderID = #orderID
)
END

How do I check whether data is there or not in more than one sql table in one script?

I have more than 3 sql tables.
now i'm trying to select count(*) from all tables but how can i do this?.
I want to know whether data is present in all tables or not
I need to check the row count from previous business day ~15% for any table and it sends an email alert
I tried like following please help me to complete
PROCEDURE [dbo].[SendEmail_WSOTableDataAlert]
AS
BEGIN
declare #err int
IF NOT EXISTS (select 1 from T1) OR
NOT EXISTS (select 1 from T2)
BEGIN
set #error=1
END
//here i need to show which table is having empty data how can i do this please help
SET #tableHTML = #tableHTML + +
'</TABLE>' + #EmailFooter;
#error =1
then
send mail
END
Select
case when count(*) = 0 then
'No rows'
else
'Has rows'
end
FROM
(
Select * from #table1
UNION ALL
Select * from #table2
UNION ALL
Select * from #table3
) t
UPDATE
This makes sure all of then have at least one row and fail if any of them does not have record
Select
case when count(*) = 0 then
'No rows'
else
'Has rows'
end
FROM
(
Select top 1 1 found from #table1
intersect
Select top 1 1 found from #table2
intersect
Select top 1 1 found from #table3
) t
You can try multiplying the flags indicating zero counts together. If any of them is zero, the result will be zero.
select (case when (select count(*) from table1)=0 then 0 else 1 end
*case when (select count(*) from table2)=0 then 0 else 1 end
*case when (select count(*) from table3)=0 then 0 else 1 end) as no_zeros
If you would like to know which table has all zeros, you could transform the query as follows:
select (case when (select count(*) from table1)=0 then 1 else 0 end
+case when (select count(*) from table2)=0 then 2 else 0 end
+case when (select count(*) from table3)=0 then 4 else 0 end
+case when (select count(*) from table4)=0 then 8 else 0 end) as no_zeros
Use powers of two (1, 2, 4, 8, 16, 32, and so on) as your flags. Ones 1 in the binary representation of the result will tell you which tables have no records.
(select count() from table1 )
union all
(select count() from table2 )
union all
(select count(*) from table3 )
And then loop through the rows of the result
declare #count1 int
select #count1 = count(*)
from table1
declare #count2 int
select #count2 = count(*)
from table2
declare #count3 int
select #count3 = count(*)
from table3
if (#count1 + #count2 + #count3 = 0)
--do something
else
--do something else
You can use the EXISTS keyword to efficiently check if there is any data in a table.
IF NOT EXISTS (SELECT 1 FROM Table1) OR NOT EXISTS (SELECT 1 FROM Table2) OR NOT EXISTS (SELECT 1 FROM Table3)
BEGIN
/* do something */
END