Select to pull Zip code based both foreign and domestic - sql

I need to write a T-SQL procedure where the parameter is zip code. We've got the following parameter declared.
declare #postal_code varchar(10)
Sample data in table:
postal_codes
NULL
46383
074523632
B4H34
113601419
ZH/8600
A1G 9Z9
WN73R
Wd3 3he
89136
etc. We've got a variety of addresses some having no postal code for certain foreign countries to some having your standard 5 digit or 10 digit US postal codes.
I need to code the query in some way to say:
select *
from table_name
where postal_code = #postal_code
My initial code was this:
select *
from table_name
where (#postal_code is null or
left(ad.postal_code, 5) = #postal_code)
but this doesn't work for anything other then 5 digit ones, then I tried using 10 digit ones but the 5 digit ones didn't match. Do I need to strip spaces or other characters? I tried searching and there is a variety of solutions but I need something that works for all kinds of zip codes foreign and domestic.

Based on your last comment it sounds like you need a "starts with" query. Try this
SELECT *
FROM table_name
WHERE REPLACE(postal_code, ' ', '') LIKE REPLACE(#postal_code, ' ', '') + '%';

Related

Extract unmatched content or values

I want to extract the un-matched values in data like in (table1)
name id subject
maria 01 Math computer english
faro 02 Computer stat english
hina 03 Chemistry physics bio
The below query
Select *
from table1
where subject like ‘%english%’ or
subject like ‘%stat%’
returns first two rows that are matched with the criteria.
But I just need to extract the un-matched values from column (subject) like below output
unmatched
math computer
computer
chemistry physics bio
(Because in the first row only math computer values are not matching, in the second row two matches and in third row there are no matches).
can i get that output??
With REPLACE you eliminate all occurrences of the values 'english' and/or 'stat':
SELECT
trim(
replace(replace(replace(subject, 'english', ''), 'stat', ''), ' ', '')
) unmatched
FROM tablename;
The final trim and replace will remove double spaces from the result and spaces from the start and the end.
You have a poor table design. You should be storing lists as separate rows in another table -- a so-called "junction" or "association" table. SQL has a great data type for storing lists. It is called a "table" not a "string".
That said, sometimes we are stuck with other peoples really, really bad choices of data model.
If so, you can use replace() and trim() to get the list you want. I would do:
SELECT trim(replace(replace(' ' || subject || ' ', ' english ', ' '
), ' stat ', ''
), ' ', ' '
) as unmatched
FROM tablename;
This easily generalizes to more values, without worrying about introducing adjacent spaces.

SQL: count occurrences for each row

I have an SQL table called Codes with a primary column code of type String.
I also have another table called Items with a column codestring also of type String. This entry always contains a string with some of the codes of the above table separated by spaces.
Now I want to get all codes and their number of Items containing the respective code. Can I do that?
Codes:
code|...
----|---
"A0A"|
"A0B"|
...|
Items:
...|codestring
----|---------
|"A0A C2B F1K"
|"A0C D2S H3K"
|...
Output:
Codes:
code|...|noOfItems
----|---|---------
"A0A"|...|5
"A0B"|...|10
...|...|...
Assuming all the codes are distinct (or at least no code is a substring of another code), you can use the LIKE operator:
(untested)
SELECT codes.code, count(*)
FROM codes LEFT JOIN items ON items.codestring LIKE '%' + codes.code + '%'
GROUP BY codes.code;
You have a horrible data format and should fix it. The mapping to codes should have a separate row for each code.
If the codes are all three characters, then L Scott Johnson's answer is close enough. Otherwise, you should take the delimiter into consideration:
SELECT c.code, count(i.codestring)
FROM codes c LEFT JOIN
items i
ON ' ' || i.codestring || ' ' LIKE '% ' || c.code || ' %'
GROUP BY c.code;
Note other fixes to the code:
The concatenation operator is the standard ||.
The count() will return 0 if there are no matches.

What is the best way to return results similar to the input?

In my database I am selecting from a field containing Dillon Brookfield. I tried searching for brookfield with the following statement thinking LIKE would select the data, but it didn't work.
SELECT *
FROM [Reports]
WHERE ([VisitorName] LIKE '%' + #VisitorName + '%'
OR [PlateNumber] = #PlateNumber)
I record people who have been banned from a property along with their plate (if known), but if their name is not put in exactly it doesn't return the value. What would be the best way to return similar results?
This is more like a comment, but there is code inside and the comment only allows one #.
What data type is your #PlateNumber? Is it CHAR or VARCHAR? it can make a difference. Like these tests.
DECLARE #char NCHAR(20) = 'space';
SELECT '%'+#char+ '%',IIF('space' Like '%'+#char+ '%', 1,0);
DECLARE #varchar NVARCHAR(20) = 'space';
SELECT '%'+#varchar+ '%',IIF('space' Like '%'+#varchar+ '%', 1,0);
The first SELECT will give you
'%space %',0. -- there will be 15 blank character between space and %
The second SELECT will give you
'%space%', 1.
Create fulltext index. Search names/addresses and other similar fields with fulltext search - it'll be faster and you can find all names - Dillon Brookfield vs Brookfield Dillon.

SQL- Remove Trailing space and add it to the beginning of the Name

Was working on SQL-EX.ru exercises.
There is one question for DML that I could not do, but I cannot proceed to the next one, until this one is done.
the question itself: All the trailing spaces in the name column of the Battles table remove and add them at the beginning of the name.
My code:
Update Battles
set name=concat(' ',(LTRIM(RTRIM(name))))
The system does not let it go through, I understand that I am using ' ' for the concat, whereas I need to use the stuff that got trimmed. And I have no idea how...
Any help would be very much appreciated
Try Something Like:-
set name = lpad(trim(name), length(trim(name))+4, ' ')
Here use TRIM to remove space from both side. use LPAD to add something on left side with n (4) chars
I'm not familiar with SQL-EX.ru, but if it's Oracle compatible and you can use regular expressions (or you are at that point in the training) here's a way. Maybe it'll give you an idea at least. The first part is just setup and uses a WITH clause to create a table (like a temp table in memory, actually called a Common Table Expression or CTE) called battles containing a name column with 2 rows. Each name column datum has a different number of spaces at the end. Next select from that column using a regular expression that uses 2 "remembered" groups surrounded by parentheses, the first containing the string up to until but not including the first space, the second containing 0 or more space characters anchored to the end of the line. Replace that with the 2nd group (the spaces) first, followed by the first group (the first part of the string). This is surrounded by square brackets just to prove in the output the same spaces were moved to the front of the string.
SQL> with battles(name) as (
select 'test2 ' from dual union
select 'test1 ' from dual
)
select '[' || regexp_replace(name, '(.*?)([ ]*)$', '\2\1') || ']' fixed
from battles;
FIXED
----------------------------------------------------------------------------
[ test1]
[ test2]
SQL>
I hope this solution can be applied to your problem or at least give you some ideas.
Try this:
set name = case when len(name) > len(rtrim(name))
then replicate(' ', len(name) - len(rtrim(name))) + rtrim(name)
else name
end
update battles
set name = case when (len(name+'a')-1) > len(rtrim(name))
then
replicate(' ',
(len(name+'a')-1) - len(rtrim(name))) + rtrim(name)
else name
end
Len() doesn't count trailing spaces. So using (len(name+'a')-1).
Simplest answer:
UPDATE Battles
SET name = SPACE(DATALENGTH(name)-DATALENGTH(RTRIM(name))) + RTRIM(name)
But only works because name is VARCHAR.
More generic is to do:
UPDATE Battles
SET name = SPACE(len(name+'x')-1-len(RTRIM(name))) + RTRIM(name)
simple example below ... enjoy :)
update battles set name =
Space( DATALENGTH(name) - DATALENGTH(rtrim(name))) + rtrim(name)
where date in ( select date from battles)

SQL Server 2005- Add area code to records shorter than 10 characters

Can anyone come up with a SQL routine or ideas to systematically append an area code to the beginning of every field in our SQL Server 2005 database that does not have an area code in it?
Perhaps someone could tell us how to return only rows that are less than 10 characters long and how to append the 3 digit area code to the beginning of each field string?
Thanks!
DECLARE #AreaCode char(3)
SET #AreaCode = 'XXX'
UPDATE myTable
SET myField = #AreaCode + myField
WHERE LEN(myField) < 10
AND myField NOT LIKE #AreaCode + '%'
This will work with SQL Server.
Ideally, the area code would be a separate column in your database. Since it's not designed that way though:
UPDATE
PhoneNumbers
SET
phone_number = '123' + phone_number
WHERE
LEN(phone_number) = 7
Of course, if people have formatted the phone numbers then this won't work. I would need to know more about the data that's in your table. You might have to do something like:
UPDATE
PhoneNumbers
SET
phone_number = '(123) ' + phone_number
WHERE
LEN(REPLACE(REPLACE(REPLACE(REPLACE(phone_number, '-', ''), '(', ''), ')', ''), '.', '') = 7
If people typed in stuff like "ext. 7" then that would further complicate things. See why it's better to break out a phone number instead of just having one column? ;)