Where clause to search for muliple items [duplicate] - sql-server

This question already has answers here:
SQL Logic Operator Precedence: And and Or
(5 answers)
Closed 9 months ago.
I have a table that has a problem name field and a Jurisdiction name field. I want to search for multiple problem names that fall under the same Jurisdiction name.
SELECT TOP (100000) [Master_Incident_Number]
,[Response_Date]
,[Problem]
,[Location_Name]
,[Address]
,[Apartment]
,[City]
,[Jurisdiction]
,[MethodOfCallRcvd]
,[Call_Disposition]
,[CallTaking_Performed_By]
,[CallClosing_Performed_By]
FROM [Reporting_System].[dbo].[Response_Master_Incident]
where Jurisdiction like 'Sector 5%'
and Response_Date >= '2022-01-01 00:00:00.000'
and Problem like 'Building / Security Check-LCL'
or Problem like 'Park and Walk-LCL'
When I run this I get returns that don't match what I put in for the Jurisdiction like 'Sector 5%'". How can I get it to only return items with the "Jurisdiction like" field being 'Sector 5%' only.
If I only do a search for only one problem name type, the search works and only returns Jurisdictions with the name like "Sector 5". But If I add an additional problem name type it returns all Jurisdiction Names with those 2 problem name types.

It's always the OR condition in these cases. Operator precedence here doesn't work the way you think it should. You need parentheses:
where Jurisdiction like 'Sector 5%'
and Response_Date >= '2022-01-01 00:00:00.000'
and (Problem like 'Building / Security Check-LCL'
or Problem like 'Park and Walk-LCL')
But since there are no wildcards in either of those checks, we can also simplify it like this:
where Jurisdiction like 'Sector 5%'
and Response_Date >= '2022-01-01 00:00:00.000'
and Problem IN ('Building / Security Check-LCL','Park and Walk-LCL')

Related

Extracting Data between two characters with T-SQL [duplicate]

This question already has answers here:
Using T-SQL, return nth delimited element from a string
(14 answers)
Closed 2 years ago.
I do not have access to write to a database, queries are limited to retrieval only. CTEs are not allowed. Cannot write functions. (Here's a document of what I'm limited to https://help.salesforce.com/articleView?id=mc_as_sql_reference.htm&type=5)
Here's an example of a string I'm working with, I'm looking to extract the email address, where I consistently know that the email will begin at the fourth |, and end at the fifth |.
D||John Smith|EML|test#gmail.com|Y|2014/01/03 17:14:01.000000|
This is what I tried so far, it's not able to return any email addresses for me
SELECT
CASE
WHEN CHARINDEX('|',AllData) > 0
THEN SUBSTRING(AllData, CHARINDEX('|', AllData, 22) + 1, ABS((CHARINDEX('|', AllData, CHARINDEX('#', AllData))) - (CHARINDEX('|', AllData, 22) + 1)))
ELSE 'NotWorking'
END AS email
FROM
[test_file]
I would suggest string_split():
select s.value
from test_file tf cross apply
string_split(alldata, '|') s
where s.value like '%#%.%';
This doesn't extract the fourth value. It extracts any value that looks like an email -- but it is pretty simple code that should work.

Compiler error Select Single Count when in Loop SQL

I have made a table where the material number, material text and so on have been added (selected_materials). Now I wanted to create a loop with this table so that it counts in the EKPO table how often the material number was mentioned in order to use it afterwards.
For the below code, the compiler says that WHERE <selected_material>-matnr is invalid, even though WRITE: ... <selected_material>-matnr = ... is valid.
LOOP AT selected_materials ASSIGNING <selected_material>.
DATA: lv_count TYPE i.
SELECT SINGLE COUNT(*)
From Ekpo
INTO lv_count
WHERE <selected_material>-matnr = Ekpo-matnr.
WRITE: <selected_material>-maktx, <selected_material>-matnr, <selected_material>-meins, <selected_material>-msehl, <selected_material>-ekpo_count.
NEW-LINE.
ENDLOOP.
Your WHERE condition is not correct, it has to be like this:
SELECT COUNT( * )
FROM ekpo
INTO lv_count
WHERE matnr EQ <selected_material>-matnr.
Please note SINGLE is also removed, as (I guess) the question is, how many entries are in EKPO for the material number (SELECT COUNT( * )...) and not, if there is at least one at all (SELECT SINGLE COUNT( * )...)
One more thing: In the WRITE, you display the field: -ekpo_count, however in the SELECT COUNT( * ) lv_count is used.
Before ABAP 7.40 SP 05, the operand on the left of the operator had to be a column name (cf József Szikszai answer).
From ABAP 7.40 SP 05, there is the "strict mode" which allows more complex SQL features. The strict mode is mainly activated by using the # character before the names of ABAP variables, like this:
SELECT COUNT( * )
FROM ekpo
WHERE #lv_matnr = ekpo~matnr
INTO #lv_count .
NB: if a column name is used on the right side the "table alias" is required (ekpo~matnr) and in strict mode the INTO clause is to be positioned at the end (tested with ABAP 7.52)

Query based on a conditional parameter?

I need to run a query that pulls client machine information into PowerBI from SQL Server based on required and non required parameters.
I have the parameters set up but am unable to get my SQL code to work. My two parameters are SelectClient1 and SelectClient2. Some clients have multiple names and usually an acronym abbreviation such as Joe's Construction, Joe's Construction LLC, and JCLLC. I need to be able to bring back all those names.
SELECT *
FROM table1, table2
WHERE table1.InspectionId = table2.InspectionId
AND OwnerName like '%"&SelectClient1&"%'
OR OwnerName like '%"&SelectClient2&"%'
My issue with the code above is sometimes I will leave SelectClient2 blank. In this case I would need the code to work and only bring back where owner is like SelectClient1.
Return something like this...
InspectionID Client Machine Severity
1 "Joe's Construction LLC" A High
2 "Joe's Construction LLC" B Low
3 "Joe's Construction" A Low
4 "JCLLC" A Medium
5 "JCLLC" B Medium
You are struggling here because you don't have any parenthesis around your predicates. If you used "modern" join structure this wouldn't matter in your query. Here is what your query would look like using ANSI-92 style joins and parameters. Please note that when you have a leading wildcard in a predicate like this you have rendered the query nonSARGable and no indexing is going to help.
SELECT *
FROM table1
join table2 on table1.InspectionId = table2.InspectionId
WHERE OwnerName like '%' + #SelectClient1 + '%'
OR OwnerName like '%' + #SelectClient2 + '%'

Crystal Reports command not working

I have a crystal report connected to a table with a command which has parameters, this command query is working
SELECT
date1,
car_num,
ar_dromologiou,
Sum(kilomtres) As ksum,
sum(posostita_ltitra) as sumpos,
sum(shmaia) as sumkom,
sum(sinokomsim) AS x3
FROM
Table_1
WHERE
date1 BETWEEN {?d1} AND {?d2}
GROUP BY
date1,
car_num,
ar_dromologiou;
this doesn't work
SELECT
date1,
car_num,
ar_dromologiou,
Sum(kilomtres) As ksum,
sum(posostita_ltitra) as sumpos,
sum(shmaia) as sumkom,
sum(sinokomsim) AS x3
FROM
Table_1
WHERE
car_num LIKE {?c1} AND
date1 BETWEEN {?d1} AND {?d2}
GROUP BY
date1,
car_num,
ar_dromologiou;
Where is the fault?
Thank you all for the answers , I found that the values where in non english characters and crystal Reports wants some Extra configuration for this, didn't find yet but when I insert a record with english characters and in the parameter input english chars it showed the record, so something about the character encoding.
The problem seems to be in your where clause where you compare car_num.
If you pass in your parameter {?c1} and it doesn't include any wildcard charaters like % or _ you will only get exact matches.
Use wildcard characters appropriate for your use case, e.g.
WHERE
car_num LIKE {?c1} + '%' AND
date1 BETWEEN {?d1} AND {?d2}
This will match all rows where car_num starts with the value of your parameter {?c1}.
You may want to have a look at the documentation for the LIKE operator.

How to use REPLACE with string containing apostrophe? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Replace single quote in sql server
So I'm trying to use the following code:
UPDATE TableName
SET FieldName = REPLACE(FieldName, 'SearchFor', 'ReplaceWith');
It works wonderfully for what I need to do, except for the fact that what I need to search for is "valid driver's license". That apostrophe doesn't seem to agree with the code. I tried doing this:
'valid driver''s license'
...but that doesn't seem to work either. I'm getting the following error:
Argument data type text is invalid for argument 1 of replace function.
If anyone has dealt with this before, I would love some help! This would save me so much time, rather than updating each record by hand. -__-
Ellie
The error tells you exactly what the problem is. FieldName is a column of type text, which doesn't work with the REPLACE function. Try casting the first param as VARCHAR(MAX) first, and it should work. IE:
UPDATE TableName
SET FieldName = REPLACE(CAST(FieldName AS VARCHAR(MAX)), 'SearchFor', 'ReplaceWith');
That's funny. I just ran into this exact thing a few minutes ago. It turns out I had to change this:
UPDATE TableName
SET FieldName = REPLACE(FieldName, 'SearchFor', 'ReplaceWith');
to this:
UPDATE TableName
SET FieldName = REPLACE(cast(FieldName as varchar(5000)), 'SearchFor', 'ReplaceWith');
You must escape the single quote with a slash.
UPDATE TableName
SET FieldName = REPLACE(FieldName, 'Isn\'t', 'Is not');

Resources