Assign range to variable using between - tsql

I have the following decitiontree:
declare #placeholder varchar(20)
If #Number1 = 1
AND #Number2 = 0
BEGIN SET #placeholder = 'NULL'
END
ELSE IF #Number1 = 1
AND #Number2 > 0
BEGIN SET #placeholder = Between (#Number2*10) AND (#Number2*10+9)
END
ELSE
BEGIN
SET #placeholder = #Othervariable
END
I need the Variable for the query:
SELECT * FROM Table
WHERE #Placeholder is null or ID = #placeholder.
But the 'Between' part is not working. Can anyone help me with it?

This won't work in SQL server - there is no variable type that holds something like lambda expression, say Between (#Number2*10) AND (#Number2*10+9).
One way is to store this in string (say, nvarchar(max)) and execute using exec() or sp_executesql().
The other (usually more optimized) way is to form the main expression to include sub-expressions along with exclusion criteria.
Here is an example:
DECLARE #Number1 int = 1 -- input variable 1
DECLARE #Number2 int = 1 -- input variable 2
DECLARE #excl1 bit = 0 -- exclusion criteria 1 (ec1)
DECLARE #excl2 bit = 0 -- exclusion criteria 2 (ec2)
-- fill excl. crit.
SET #excl1 = CASE WHEN #Number1 = 1 AND #Number2 = 0 THEN 1 ELSE 0 END
SET #excl2 = CASE WHEN #Number1 = 1 AND #Number2 > 0 THEN 1 ELSE 0 END
-- just output to see what's happening
PRINT #Number1
PRINT #Number2
PRINT #excl1
PRINT #excl2
SELECT *
FROM Table
WHERE
-- if ec1 is active, we apply sub-expression 1
(#excl1 = 0 OR
(#excl1 = 1 AND ID IS NULL))
AND
-- if ec2 is active, we apply sub-expression 2
(#excl2 = 0 OR
(#excl2 = 1 AND ID BETWEEN #Number2 * 10 AND #Number2 * 10 + 9))

Related

Is possible change operator = by a variable inside a function POSTGRESQL?

I don't know if this is possible, but this is the question. I try to change operator = by > if paramvalue = 0
AS $BODY$
declare
operator text;
begin
operator:='=';
if (paramvalue = 0) then
operator:='>';
end if;
select * from tablaname where id #operator 20
thanks!
I think overloading an operator is more complex than what you need for this behavior. You could try using a CASE statement instead.
SELECT *
FROM tablename
WHERE CASE WHEN paramvalue = 0
THEN id > 20
ELSE id = paramvalue
END
;
If you really want to overload an operator I suggest taking a look at the postgres documentation here.
REMARK NOT TESTED !!
In your scenario solution could be...:
.....
if (paramvalue = 0) then
select * from tablaname where id > 20
Else
select * from tablaname where id = 20
end if;
Please read this 9.16. Conditional Expressions
And this would be rather:
CASE WHEN paramvalue = 0 THEN select * from tablaname where id > 20
ELSE select * from tablaname where id = 20
END

Determine Group By from Parameter -

How is it that this is valid:
ALTER PROCEDURE [StoredProcedure]
#abcID int = null -- optional param
SELECT columnJ, columnK, Count(eID) AS Num, Sum(OutXYZ) as TotalProdXYZ, Sum(RawXYZ) as TotalRawXYZ
FROM [v_ViewTable]
WHERE (#abcID IS NULL OR (abcID = #abcID))
GROUP BY columnJ, columnK
But then this is throwing a "columnJ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
ALTER PROCEDURE [StoredProcedure]
#abcID int = null -- optional param
-- if 0: Group by columnJ, columnK
-- else: Group by columnK, columnJ
, #Grouping int = null
SELECT columnJ, columnK, Count(eID) AS Num, Sum(OutXYZ) as TotalProdXYZ, Sum(RawXYZ) as TotalRawXYZ
FROM [v_ViewTable]
WHERE (#abcID IS NULL OR (abcID = #abcID))
GROUP BY
CASE WHEN #Grouping = 0 THEN columnJ ELSE columnK END
,CASE WHEN #Grouping = 0 THEN columnK ELSE columnJ END
What's wrong with my CASE statement? Basically, if #Grouping = 0, I want the group by to be J, K if anything else, it should be K, J
Thanks in advance for any help!
As the message says columnJ and columnK are not contained in either an aggregate function or the GROUP BY clause in the second case. You should use field or the exact expression in select list AS IS in the GROUP BY section.
So the following statement will be ok:
SELECT CASE WHEN #Grouping = 0 THEN columnJ ELSE columnK END,
CASE WHEN #Grouping = 0 THEN columnK ELSE columnJ END,
Count(eID) AS Num, Sum(OutXYZ) as TotalProdXYZ, Sum(RawXYZ) as TotalRawXYZ
FROM [v_ViewTable]
WHERE (#abcID IS NULL OR (abcID = #abcID))
GROUP BY
CASE WHEN #Grouping = 0 THEN columnJ ELSE columnK END
,CASE WHEN #Grouping = 0 THEN columnK ELSE columnJ END

wrong result with floating numbers

I have this table with 1 records. Im trying to compute something call Puntaje, to get the Puntaje Result I have to follow the following formula:
Puntaje = (Infracciones * 10) / Horas
Horas = Segundos / 60 / 60
I wrote the following script, but I have some doubt and problem.
1) Is there another way to assign the values to #variables or another way to compute the sum?
2) Why the Puntaje result is 0.00, have to be: 0.854
Im using MS SQL Server 2012
Can someone help me to resolve this? Thank you in advance.
/* content of table: #Customer_Drivers
DriverId Segundos KM QtyExcesos QtyFreAce QtyDesc Puntaje IDC
6172 717243 1782 17 0 0 0 0
*/
DECLARE #Customer_Drivers TABLE (
DriverId INT,
Segundos INT,
KM INT,
QtyExcesos INT,
QtyFreAce INT,
QtyDesc INT,
Puntaje INT,
IDC INT
);
SET NOCOUNT ON;
INSERT INTO #Customer_Drivers (DriverId, Segundos, KM, QtyExcesos, QtyFreAce, QtyDesc, Puntaje, IDC)
VALUES (6172, 717243, 1782, 17, 0, 0, 0, 0);
SET NOCOUNT OFF;
DECLARE #DriverId INT = 6172;
DECLARE #Horas INT;
DECLARE #QtyExcesos INT ;
DECLARE #QtyFreAce INT ;
DECLARE #QtyDesc INT ;
DECLARE #Infracciones INT;
DECLARE #Puntaje Decimal(18,2);
SET #Horas = (SELECT Segundos FROM #Customer_Drivers WHERE DriverId = #DriverId) / 60 / 60;
SET #QtyExcesos = (SELECT QtyExcesos FROM #Customer_Drivers WHERE DriverId = #DriverId);
SET #QtyFreAce = (SELECT QtyFreAce FROM #Customer_Drivers WHERE DriverId = #DriverId);
SET #QtyDesc = (SELECT QtyDesc FROM #Customer_Drivers WHERE DriverId = #DriverId);
SET #Infracciones = (#QtyExcesos + #QtyFreAce + #QtyDesc);
SET #Puntaje = ( #Infracciones * 10) /#Horas;
PRINT #Horas
PRINT #QtyExcesos
PRINT #QtyFreAce
PRINT #QtyDesc
PRINT #Puntaje
/* OUTPUT
199 -- #Horas
17 -- #QtyExcesos
0 -- #FreAce
0 -- #QtyDesc
0.00 -- #Puntaje must be = 0.854
*/
Even though #Puntaje is declared as Decimal(18,2), that doesn't mean your calculation will be treated as a decimal. The problem is that ( #Infracciones * 10) / #Horas is using all integers so this expression will result in the integer value 0. Then this integer 0 is converted to a decimal and stored in #Puntaje.
To fix this, you need to convert part of the expression to a decimal first so that the result will be a decimal:
SET #Puntaje = ( CAST(#Infracciones AS Decimal(18,2)) * 10) / #Horas
You are using integers in your calculation, so the result will be rounded off (or truncated) to the nearest integer. Use decimal values, or use 'cast' :
#Puntaje = (cast(#Infracciones as decimal(18,2)) * 10.0) / cast(#Horas as decimal(18,2))
Check my syntax - just typed this on without trying it
1) You can use SELECT #Horas = Segundos/3600, #QtyExcesos = QtyExcesos ... FROM [RS_Reports].[dbo].[Customer_Drivers] WHERE DriverId = #DriverId. This should work providing that there is one line of results.
2) Already answered by others, you have to divide by decimal to get a decimal, i.e. you'll have to convert #Horas to Decimal
From what I've learned. #variable should be some parameters light input parameter and output parameter.... Try to execute your Stored Procedure and see what you got in SQL Server Management Studio.
There should be a return value.

tsql how to validate a number's scale

I need to validate the number of digits to the right of the decimal (the scale)
0, is a valid number in any of the places (tenths, hundredths, thousandths, etc.).
Any tips or tricks?... w/o an extensive regex library, and no built in function, I would prefer a function that accepts the number, the number of places the scale should equal, and then return a bit.
Following up with Maess's suggestion I came up with this:
CREATE FUNCTION [dbo].[GetScale]
(
#tsValue varchar(250)
, #tiScale int
)
RETURNS int
AS
BEGIN
DECLARE
#tiResult int
, #tiValueScale int
SET #tiResult = 0
SELECT #tiValueScale = LEN( SUBSTRING ( #tsValue, PATINDEX('%.%', #tsValue) + 1, LEN(#tsValue) ) )
IF (#tiValueScale = #tiScale)
SET #tiResult = 1
RETURN #tiResult
END
GO
Seems to work as desired. Thanks for the help.
Just as a followup... i ran into an issue where a number didnt have a decimal (which returns the patindex to 0) and the number was the same size as the scale, it would return a false positive... so i add an additional select from the patindex to determine if it does exist or not... it now looks like this:
- =============================================
ALTER FUNCTION [dbo].[GetScale]
(
#tsValue varchar(250)
, #tiScale int
)
RETURNS int
AS
BEGIN
DECLARE
#tiResult int
, #tiValueScale int
, #tiDecimalExists int
SET #tiResult = 0
SET #tiDecimalExists = 0
SELECT #tiDecimalExists = PATINDEX('%.%', #tsValue)
IF (#tiDecimalExists != 0)
BEGIN
SELECT #tiValueScale = LEN( SUBSTRING ( #tsValue, #tiDecimalExists + 1, LEN(#tsValue) ) )
IF (#tiValueScale = #tiScale)
SET #tiResult = 1
END
RETURN #tiResult
END
I tried Anthony's solution with some success, but there is some undesirable side effects when the first whole number is 9.
For example...
select 0.11 as fraction, Math.NumberOfDecimalPlaces(0.11) dp union
select 9.1, Math.NumberOfDecimalPlaces(9.1) union
select 9.01, Math.NumberOfDecimalPlaces(9.01) union
select 9.0, Math.NumberOfDecimalPlaces(9.0) union
select 99.0, Math.NumberOfDecimalPlaces(99.0) union
select 10999.0, Math.NumberOfDecimalPlaces(10999.0) union
select 8.0, Math.NumberOfDecimalPlaces(8.0) union
select 0, Math.NumberOfDecimalPlaces(0)
Produces...
0.00 0
0.11 2
8.00 0
9.00 -1
9.01 2
9.10 1
99.00 -2
10999.00 -3
Which shows some incorrect calculations when 9 is the first whole number.
I've made a small improvement to Anthony's original function.
CREATE FUNCTION [Math].[NumberOfDecimalPlaces]
(
#fraction decimal(38,19)
)
RETURNS INT
AS
BEGIN
RETURN FLOOR(LOG10(REVERSE(ABS(#fraction % 1) +1))) +1
END
This simply strips of the whole number part of the fraction. Which when implemented produces...
0.00 0
0.11 2
8.00 0
9.00 0
9.01 2
9.10 1
99.00 0
10999.00 0
The correct result
CREATE FUNCTION dbo.DecimalPlaces(#n decimal(38,19))
RETURNS int
AS
BEGIN
RETURN FLOOR(LOG10(REVERSE(ABS(#n % 1) + 1))) + 1
END
Edit (Feb 5 '15):
Thanks sqlconsumer. I have included your fix for nines before the decimal point.

How to conditionally filter on a column in a WHERE clause?

OK, the umpteenth conditional column question:
I'm writing a stored proc that takes an input parameter that's mapped to one of several flag columns. What's the best way to filter on the requested column? I'm currently on SQL2000, but about to move to SQL2008, so I'll take a contemporary solution if one's available.
The table queried in the sproc looks like
ID ... fooFlag barFlag bazFlag quuxFlag
-- ------- ------- ------- --------
01 1 0 0 1
02 0 1 0 0
03 0 0 1 1
04 1 0 0 0
and I want to do something like
select ID, name, description, ...
from myTable
where (colname like #flag + 'Flag') = 1
so if I call the sproc like exec uspMyProc #flag = 'foo' I'd get back rows 1 and 4.
I know I can't do the part in parens directly in SQL. In order to do dynamic SQL, I'll have to stuff the entire query into a string, concatenate the #flag param in the WHERE clause and then exec the string. Aside from the dirty feeling I get when doing dynamic SQL, my query is fairly large (I'm selecting a couple dozen fields, joining 5 tables, calling a couple of functions), so it's a big giant string all because of a single line in a 3-line WHERE filter.
Alternately, I could have 4 copies of the query and select among them in a CASE statement. This leaves the SQL code directly executable (and subject to syntax hilighting, etc.) but at the cost of repeating big chunks of code, since I can't use the CASE on just the WHERE clause.
Are there any other options? Any tricky joins or logical operations that can be applied? Or should I just get over it and exec the dynamic SQL?
There are a few ways to do this:
You can do this with a case statement.
select ID, name, description, ...
from myTable
where CASE
WHEN #flag = 'foo' then fooFlag
WHEN #flag = 'bar' then barFlag
END = 1
You can use IF.
IF (#flag = 'foo') BEGIN
select ID, name, description, ...
from myTable
where fooFlag = 1
END ELSE IF (#flag = 'bar') BEGIN
select ID, name, description, ...
from myTable
where barFlag = 1
END
....
You can have a complicated where clause with a lot of parentheses.
select ID, name, description, ...
from myTable
where (#flag = 'foo' and fooFlag = 1)
OR (#flag = 'bar' and barFlag = 1) OR ...
You can do this with dynamic sql:
DECLARE #SQL nvarchar(4000)
SELECT #SQL = N'select ID, name, description, ...
from myTable
where (colname like ''' + #flag + 'Flag'') = 1'
EXECUTE sp_ExecuteSQL #SQL, N''
There are more, but I think one of these will get you going.
"Alternately, I could have 4 copies of the query and select among them in a CASE statement."
You don't need to copy your entire query 4 times, just add all the possibilities into the where clauses in your single copy of the query:
select ID, name, description, ...
from myTable
where (#flag = 'foo' and fooFlag = 1) OR (#flag = 'bar' and barFlag = 1) OR ...
What I would do is CASE some variables at the beginning. Example:
DECLARE
#fooFlag int,
#barFlag int,
#bazFlag int,
#quuxFlag int
SET #fooFlag = CASE WHEN #flag = 'foo' THEN 1 ELSE NULL END
SET #barFlag = CASE WHEN #flag = 'bar' THEN 1 ELSE NULL END
SET #bazFlag = CASE WHEN #flag = 'baz' THEN 1 ELSE NULL END
SET #quuxFlag = CASE WHEN #flag = 'quux' THEN 1 ELSE NULL END
SELECT ID, name, description, ...
FROM myTable
WHERE (fooFlag >= ISNULL(#fooFlag, 0) AND fooFlag <= ISNULL(#fooFlag, 1))
AND (barFlag >= ISNULL(#barFlag, 0) AND barFlag <= ISNULL(#barFlag, 1))
AND (bazFlag >= ISNULL(#bazFlag, 0) AND bazFlag <= ISNULL(#bazFlag, 1))
AND (quuxFlag >= ISNULL(#quuxFlag, 0) AND quuxFlag <= ISNULL(#quuxFlag, 1))
The good thing about this query is that, because the possible values for "flags" are bounded, you can calculate all your conditionals as prerequisites instead of wrapping columns in them. This guarantees a high-performance index seek on whichever columns are indexed, and doesn't require writing any dynamic SQL. And it's better than writing 4 separate queries for obvious reasons.
You could have a parameter for each possible flag column, then check if the parameter is null or the value in the column is equal to the parameter. Then you pass in a 1 for the flags that you want to check and leave the others null.
select id, name, description, ...
from myTable
where (#fooFlag is null or fooFlag = #fooFlag) AND
(#barFlag is null or barFlag = #barFlag) AND
...
Honestly, though, this seems like an ideal candidate for building a dynamic LINQ query and skipping the SPROC once you get to SQL2008.
int should be accepted as varchar value
declare #CompanyID as varchar(10) = '' -- or anyother value
select * from EmployeeChatTbl chat
where chat.ConversationDetails like '%'+#searchKey+'%'
and
(
(0 = CASE WHEN (#CompanyID = '' ) THEN 0 ELSE 1 END)
or
(chat.CompanyID = #CompanyID)
)
working
when the companyID is present , then filtration based on it is done, other wise , filtration is skipped.
where
case when #value<>0 then Field else 1 end
=
case when #value<>0 then #value else 1 end