comparing three variables - sql

I have three integer variables: firstCount, secondCount, thirdCount. I need to compare it and to output the result. I'm bad at SQL, but C# code is something like this:
if(firstCount == secondCount == thirdCount)
return true;
else
return false;

One way (2008 syntax).
SELECT CAST(CASE
WHEN COUNT(DISTINCT C) = 1 THEN 1
ELSE 0
END AS BIT)
FROM (VALUES (#firstCount),
(#secondCount),
(#thirdCount)) t (C)

declare #first int
, #second int
, #third int
select #first = 0
, #second = 0
, #third = 0
select case when (#first = #second) AND (#second = #third) THEN 1 ELSE 0 END

Following is one way to do it but after reading #meagar's comment, I find that solution to be more elegant. Just waiting for him to turn it into an answer...
DECLARE #firstcount INTEGER
DECLARE #secondcount INTEGER
DECLARE #thirdcount INTEGER
SET #firstcount = 1
SET #secondcount = 2
SET #thirdcount = 3
IF #firstcount <> #secondcount SELECT 0
ELSE IF #secondcount <> #thirdcount SELECT 0
ELSE SELECT 1

You are wanting to say If Firstcount is equal to second count, and secondcount is equal to third count return true.
You can just do
DECLARE #a INT = 2
DECLARE #b INT = 2
DECLARE #c INT = 2
IF (#a = #b AND #a = #c)
BEGIN
Print('true')
END
ELSE
BEGIN
Print('false')
END
Although it makes no difference you dont need to test B = C because A = C is exactly the same thing since all 3 values have to be the same.

Try the code ,
if ( (firstCount = secondCount) and (secondCount = thirdCount) and (firstCount = ThirdCount) )
return true;
else
return false;

Related

SQL Server - CASE on where clause

I'm working on a stored procedure that is a select query. Under the WHERE clause I am filtering the return results to return only if there is a PageTitle= 'STA'
Here is am example of my query :
#InputCountryId INT,
#InputIndustryId INT
AS
BEGIN
SELECT
r.IdCountry,
r.IdIndustry,
r.PageTitle,
r.IndustryName
From dbo.Reports r
WHERE
r.IdCountry = #InputCountryId
r.IdIndustry = #InputIndustryId
r.PageTitle = 'STA'
END
The ending condition r.PageTitle I would like it to be applied ONLY IF InputCountry = 1 if not; do not include the filter.
I've attempted this by including a CASE. I am having a syntax error any time I try and introduce this case. Is this something that is possible? Am I implementing it incorrectly?
Here is an example of the stored proc with the CASE included.
#InputCountryId INT,
#InputIndustryId INT
AS
BEGIN
SELECT
r.IdCountry,
r.IdIndustry,
r.PageTitle,
r.IndustryName
From dbo.Reports r
WHERE
r.IdCountry = #InputCountryId
r.IdIndustry = #InputIndustryId
CASE WHEN #InputCountryId = 1 THEN
r.PageTitle = 'STA'
END
END
Try it this way:
WHERE
r.IdCountry = #InputCountryId and
r.IdIndustry = #InputIndustryId and
(#InputCountryId <> 1 or r.PageTitle = 'STA')
You dont need case statement. You can use OR clause
WHERE
r.IdCountry = #InputCountryId
r.IdIndustry = #InputIndustryId
(#InputCountryId != 1 OR r.PageTitle = 'STA')
this only filters PageTitle with STA when InputCountry is 1
I can't test with your data, but here is a CASE in a WHERE clause that works.
DECLARE #Variable INT = 3
SELECT GETDATE()
WHERE 1 =
CASE
WHEN #Variable = 1 THEN 1
WHEN #Variable = 3 THEN 1
WHEN #Variable = 5 THEN 1
ELSE 0
END

Reusing Value of a subquery in Else clause

is there any way i can use the value of X in the if clause in the else clause
if #bid_value>(SELECT MAX(bid_value) AS X FROM dbo.auctionDetails WHERE status = 0 AND vehicle_id=#vid GROUP BY vehicle_id)
BEGIN
//some code
END
ELSE IF X=NULL
BEGIN
//some code
END
Why don't you create a var for the value?
DECLARE #maxValue INT
SELECT #maxValue = MAX(bid_value)
FROM dbo.auctionDetails
WHERE status = 0 AND vehicle_id = #vid
IF (#bid_value > #maxValue)
BEGIN
// some code
END
ELSE IF (#maxValue IS NULL)
BEGIN
// some code
END
A comment about how you are getting the MAX value: As you are filtering by vehicle_id = #vid, you don't need GROUP BY clause since you will get results for only one value of vahicle_id
You would typically assign the results of the query to a variable.
If you are running SQL Server:
DECLARE #max_bid_value INT;
SELECT #max_bid_value = MAX(bid_value)
FROM dbo.auctionDetails
WHERE status = 0 AND vehicle_id = #vid;
IF #bid_value > #max_bid_value
BEGIN
//some code
END
...
Note that I removed the GROUP BY clause from the original query - I think that this makes it clearer that it should always return a scalar value.
Note that if you want to check if a variable is null, you need #bid is null rather than #bid = null.
Your query should be like below :
DECLARE #X INT
SET #X = (SELECT MAX(bid_value) AS X FROM dbo.auctionDetails WHERE status = 0 AND vehicle_id=#vid);
IF #bid_value>#MAX
BEGIN
//some code
END
ELSE IF X=NULL
BEGIN
//some code
END

Update column by calling function is very slow - how to improve? SQL Server

I need to update some column by calling a function. It takes a too long time.
How can I improve it? What could be the reason it takes so long?
I realized that scalar-function takes more time than a table-function, but I have no idea how to convert this to a table function, is there perhaps another way to do this?
The code that updates:
UPDATE EDBNationalInsuranceMortgageLoad_tmp
SET IsDead = dbo.GetIsDead(IdentityNumber1, #FileId) -- the function
The code of the function:
ALTER FUNCTION [dbo].[GetIsDead]
(#IdentityNumber1 NVARCHAR(9),
#FileId INT)
RETURNS int
AS
BEGIN
DECLARE #mateIdentityNumber NVARCHAR(9);
DECLARE #fullRow1_tmp TABLE
(
IdentityNumber NVARCHAR(9),
MateIdentityNumber NVARCHAR(9),
DeathDate NVARCHAR(8)
);
DECLARE #fullRow2_tmp TABLE
IdentityNumber NVARCHAR(9),
MateIdentityNumber NVARCHAR(9),
DeathDate NVARCHAR(8)
);
DECLARE #countRows2 INT
DECLARE #isDead1 INT = 0
DECLARE #isDead2 INT = 0
SET #mateIdentityNumber = (SELECT TOP 1 MateIdentityNumber
FROM MortgageReturnParticipationBase
WHERE IdentityNumber = #IdentityNumber1
AND MortgageReturnParticipationStatusId = 1)
INSERT INTO #fullRow1_tmp
SELECT TOP 1 IdentityNumber1, IdentityNumber2, DeathDate
FROM EDBNationalInsuranceMortgageLoad_tmp
WHERE IdentityNumber1 = #IdentityNumber1
AND IsRowError = 0
AND FileId = #FileId
SET #isDead1 = (SELECT 1
FROM #fullRow1_tmp
WHERE DeathDate IS NOT NULL)
IF #mateIdentityNumber = 0
BEGIN
IF (#isDead1 = 1)
RETURN 0;
ELSE
RETURN 1;
END
ELSE
BEGIN
INSERT INTO #fullRow2_tmp
SELECT TOP 1 IdentityNumber1, IdentityNumber2, DeathDate
FROM EDBNationalInsuranceMortgageLoad_tmp
WHERE IdentityNumber1 = #mateIdentityNumber
AND IsRowError = 0
AND FileId = #FileId
SET #countRows2 = (SELECT COUNT(*) FROM #fullRow2_tmp)
IF #countRows2 = 0
RETURN 2;
SET #isDead2 = (SELECT 1 FROM #fullRow2_tmp WHERE DeathDate IS NOT NULL)
IF (#isDead1 IS NULL OR #isDead2 IS NULL OR #isDead1 = 0 OR #isDead2 = 0)
RETURN 1;
IF (#isDead1 = 1 AND #isDead2 = 1)
RETURN 0;
END
RETURN NULL;
END
I tried to convert it to a table-function, but it worked slowly:
ALTER FUNCTION dbo.GetIsDeadTableFunc (
#IdentityNumber1 nvarchar(9),
#FileId INT)
RETURNS TABLE AS RETURN
select (case when (b.MateIdentityNumber > 0 and b.MateIdentityNumber
not in (SELECT IdentityNumber1
from EDBNationalInsuranceMortgageLoad_tmp
where IsRowError=0
and FileId=#FileId))
then 2
when (b.MateIdentityNumber = 0
and DeathDate is null)
or (b.MateIdentityNumber > 0 and b.MateIdentityNumber in (SELECT IdentityNumber1
from EDBNationalInsuranceMortgageLoad_tmp
where IsRowError=0
and FileId=#FileId
and (DeathDate is null or DeathDate is not null))
and DeathDate is null)
or (b.MateIdentityNumber > 0 and b.MateIdentityNumber in (SELECT IdentityNumber1
from EDBNationalInsuranceMortgageLoad_tmp
where IsRowError=0
and FileId=#FileId
and DeathDate is null) -- אמור להיות עוד פונה והוא נמצא בקובץ חי
and DeathDate is not null) -- פונה 1 נפטר
then 1
else 0 end) as IsDead
from EDBNationalInsuranceMortgageLoad_tmp e
join MortgageReturnParticipationBase b on b.IdentityNumber = e.IdentityNumber1
WHERE e.IdentityNumber1 = #IdentityNumber1
and IsRowError=0
and FileId=#FileId
and b.MortgageReturnParticipationStatusId=1
GO

The MIN function requires 1 argument(s)

Below is the code snippet in which MIN function using. When execute below code it is giving an error.
CREATE FUNCTION [dbo].[FN_TempCalcTransportExemp]
(
#EmployeeID varchar(20),
#PayElement varchar(20),
#Month varchar(10),
#FinYear varchar(10)
)
RETURNS decimal
AS
BEGIN
DECLARE #TarnsportExemption decimal(18,2) = 0
DECLARE #TDSIsFullExemption bit
DECLARE #PermanentPhysicalDisability decimal(18,2) = 0
DECLARE #UsingComapnyCar bit
DECLARE #Conveyance decimal(18,2) = 0
DECLARE #TransYes decimal(18,2) = 0
DECLARE #TransNo decimal(18,2) = 0
DECLARE #MinConveyance decimal(18,2) = 0
DECLARE #MinTransport decimal(18,2) = 0
SELECT
#TDSIsFullExemption = TDSDetailsFullExemption,
#TransYes = TDSDetailsYes,
#TransNo = TDSDetailsNo
FROM
tbl_TDSSettingDetails
WHERE
TDSSettingsDetailID = 2
SELECT
#Conveyance = #Month
FROM
tbl_Income
WHERE
EmployeeID = #EmployeeID
AND Element = #PayElement
AND FinancialYear = #FinYear
SELECT
#UsingComapnyCar = UsingCompanyCar,
#PermanentPhysicalDisability = PermanentPhysicalDisability
FROM
tbl_Employee_TDS
WHERE
EmployeeID = #EmployeeID
AND TDSFinancialYear = #FinYear
IF (#TDSIsFullExemption = 1)
BEGIN
SET #TarnsportExemption = #Conveyance
END
ELSE
BEGIN
IF (#UsingComapnyCar = 1)
BEGIN
IF (#Conveyance = 0)
BEGIN
SET #MinConveyance = 0
END
ELSE
BEGIN
SET #MinConveyance = #Conveyance
END
IF (#PermanentPhysicalDisability = 1)
BEGIN
SET #MinTransport = #TransYes
END
ELSE
BEGIN
SET #MinTransport = #TransNo
END
SET #TarnsportExemption = MIN(#MinConveyance, #MinTransport)
END
ELSE
BEGIN
SET #TarnsportExemption = 0
END
END
RETURN #TarnsportExemption
END
Error Message:
Msg 174, Level 15, State 1, Procedure FN_TempCalcTransportExemp, Line
66
The MIN function requires 1 argument(s).
set #TarnsportExemption = MIN(#MinConveyance,#MinTransport) - The MIN function is not what you think it is.
You probably want to do something like this:
set #TarnsportExemption = CASE WHEN #MinConveyance < #MinTransport THEN
#MinConveyance
ELSE
#MinTransport
END
Another option is this:
SELECT #TarnsportExemption = MIN(val)
FROM
(
SELECT #MinConveyance as val
UNION ALL
SELECT #MinTransport as val
)
And one more option is to use the values clause:
SELECT #TarnsportExemption = MIN(val)
FROM (VALUES ( #MinConveyance), (#MinTransport)) AS value(val)
Change your min statement like below MIN. Please refer MIN (Transact-SQL)
--fROM
set #TarnsportExemption = MIN(#MinConveyance,#MinTransport)
--To
SELECT #TarnsportExemption = MIN(A) FROM (
SELECT #MinConveyance A
UNION ALL
SELECT #MinTransport
)AS AA
In SQL, MIN function will return you minimum value of a column from selected list; so you can use MIN only in inline queries.
e.g. Select min(Salary) from Tbl_Employee
So, in your case either you can use case when then or union all to get minimum value from two variables as:-
SET #TarnsportExemption = CASE WHEN #MinConveyance < #MinTransport THEN #MinConveyance ELSE #MinTransport END
OR
SELECT #TarnsportExemption = MIN(TEMPS.[VALUE])
FROM (
SELECT #MinConveyance AS VALUE
UNION ALL
SELECT #MinTransport AS VALUE
) AS TEMPS

How to set column names to a declared Variable?

I am trying to set a column name to a declared variable but i keep getting invalid column name message. what is the right syntax? Here is the query
Declare #APPSHELTER Table
(tid int Identity(1,1),App_Id Numeric,PrimaryName Varchar(300),--EmployerAdress Varchar(500), rent_amt varchar(20),house_payment_amt varchar(20),ins_amt varchar(20),utilities_amt varchar(20),Trash_Collection_amt varchar(20),Sewerage_amt varchar(20),Telephone_amt varchar(20),water_amt varchar(20),other_amt varchar(20), total varchar(20), property_taxes_amt varchar(20),insurance_amt varchar(20), other_house_amt varchar(20), gas_amt varchar(20), elec_amt varchar(20), otherfuel_amt varchar(20))
DECLARE #rent_amt_h NUMERIC
DECLARE #house_payment_amt_h NUMERIC
DECLARE #insurance_amt_h NUMERIC
DECLARE #property_taxes_amt_h NUMERIC
DECLARE #Other_house_amt_h NUMERIC
DECLARE #gas_amt_u NUMERIC
DECLARE #elec_amt_u NUMERIC
DECLARE #otherfuel_amt_u NUMERIC
DECLARE #Trash_Collection_amt_u NUMERIC
DECLARE #Sewerage_amt_u NUMERIC
DECLARE #Telephone_amt_u NUMERIC
DECLARE #water_amt_u NUMERIC
DECLARE #other_amt_u NUMERIC
DECLARE #total_u NUMERIC
insert into #APPSHELTER(App_Id,PrimaryName,rent_amt,house_payment_amt,ins_amt,utilities_amt,Trash_Collection_amt,Sewerage_amt,Telephone_amt,water_amt,other_amt,total, property_taxes_amt, insurance_amt, other_house_amt, gas_amt, elec_amt, otherfuel_amt )
select #app_id,
ISNULL((select top 1 replace(first_name,'''','''''') + ' ' + isnull(replace(middle_name,'''',''''''),'') + ' '+replace(last_name,'''','''''')
from app_member (nolock)
where app_id = #app_id and msn=1),'') AS PrimaryName,
isnull(rent_amt,'0' ) AS rent_amt,
isnull(house_payment_amt,'0') AS house_payment_amt,
isnull((insurance_amt+property_taxes_amt),'0') AS ins_amt,
--isnull(HC_Costs_amt,'0') AS utilities_amt,
isnull(gas_amt,'0') + isnull(elec_amt,'0') + isnull(otherfuel_amt,'0') as utilities_amt,
isnull(Trash_Collection_amt,'0') AS Trash_Collection_amt,
isnull(Sewerage_amt,'0') AS Sewerage_amt,
isnull(Telephone_amt,'0') AS Telephone_amt,
isnull(water_amt,'0') AS water_amt,
isnull(other_amt,'0') + isnull(other_house_amt,'0') AS other_amt,
isnull(total,'0') AS total,
isnull(property_taxes_amt,'0' ) AS property_taxes_amt,
isnull(insurance_amt,'0' ) AS insurance_amt,
isnull(other_house_amt,'0' ) AS other_house_amt,
isnull(gas_amt,'0' ) AS gas_amt,
isnull(elec_amt,'0' ) AS elec_amt,
isnull(otherfuel_amt,'0' ) AS otherfuel_amt
from Ext_App_Group_Other_Expenses APP_DEP (nolock)
WHERE APP_DEP.APP_ID=#APP_ID
SET #rent_amt_h = 'rent_amt'
SET #house_payment_amt_h = 'house_payment_amt'
SET #insurance_amt_h = 'insurance_amt'
SET #property_taxes_amt_h = 'property_taxes_amt'
SET #Other_house_amt_h = 'other_house_amt'
SET #gas_amt_u = 'gas_amt'
SET #elec_amt_u = 'elec_amt'
SET #otherfuel_amt_u = 'otherfuel_amt'
SET #Trash_Collection_amt_u = 'Trash_Collection_amt'
SET #Sewerage_amt_u = 'Sewerage_amt'
SET #Telephone_amt_u = 'Telephone_amt'
SET #water_amt_u = 'water_amt'
SET #other_amt_u = 'other_amt'
SET #total_u = 'total'
DECLARE #APPSHELTER_COUNT INT
if (rent_amt!=0 or house_payment_amt!=0 or insurance_amt != 0 or property_taxes_amt != 0 or gas_amt != 0 or elec_amt != 0 or otherfuel_amt != 0 or Trash_Collection_amt != 0 or Sewerage_amt != 0 or Telephone_amt != 0 or water_amt != 0 or other_house_amt != 0 or other_amt != 0 or total !=0)
begin
SET #APPSHELTER_COUNT = (select Count(APP_ID) FROM ext_app_group_other_expenses (nolock) WHERE APP_ID = #App_Id )
end
else
begin
SET #APPSHELTER_COUNT = 0
end
Actually, I am trying the check whether the values in these text boxes are null or not. If not I have to set the count!
2 things:
(1). I think this is erroneous - I don't see these variables declared anywhere....
if (rent_amt!=0 or house_payment_amt!=0 or insurance_amt != 0 or property_taxes_amt != 0 or gas_amt != 0 or elec_amt != 0 or otherfuel_amt != 0 or Trash_Collection_amt != 0 or Sewerage_amt != 0 or Telephone_amt != 0 or water_amt != 0 or other_house_amt != 0 or other_amt != 0 or total !=0)
(2). You defined a bunch of variables at the top #rent_amt_h, #house_payment_amt_h, etc as NUMERIC, but then at the bottom you are setting them to a string value. This will also throw an error - if you are trying to say that these are your column names, then this is not the way to do it - you aren't selecting it anywhere, either. Please clarify what you are hoping to achieve...
Please find below simplified code which seemed to meet your requirements. To test it change values from 0 to 1 in insert statement:
-- Dynamic SQL command string variable
DECLARE #cmdSQL VARCHAR(1000)
-- Column names
DECLARE #rent_amt_h VARCHAR(20) = 'App_Id'
DECLARE #house_payment_amt_h VARCHAR(20) = 'PrimaryName'
-- Count variable
DECLARE #APPSHELTER_COUNT INT
-- Make SQL command
SET #cmdSQL = '
Declare #APPSHELTER Table
(App_Id Numeric,PrimaryName Varchar(300))
insert into #APPSHELTER(App_Id,PrimaryName) values (0,0)
SELECT * FROM #APPSHELTER WHERE ' + #rent_amt_h + ' !=0 OR ' + #house_payment_amt_h + ' != 0'
-- Execute dynamic SQL
EXEC(#cmdsql)
IF ##ROWCOUNT != 0
SET #APPSHELTER_COUNT = 1
ELSE
SET #APPSHELTER_COUNT = 0
SELECT #APPSHELTER_COUNT