sqlsrv update where not all passed vars have data - insert-update

I am making a form for employees to update their demographics, address, phone, email, etc. The information is placed in a processing table that is then processed to on file on Mondays. I didn't want to place multiple lines in the processing table for one person, so the scenario that someone comes in on Tuesday with a new address and then comes back on Thursday with a new phone, gets updated on the same line.
I've done this:
UPDATE PendingProcessing
SET Street1 = ISNULL(NULLIF('{$addr1}',''), Street1),
Street2 = ISNULL(NULLIF('{$addr2}',''), Street2),
Email = IsNull(NULLIF('{$email}',''), Email),
CellPhone = IsNull(NULLIF('{$cellPhone}',''), CellPhone),
HomePhone = IsNull(NULLIF('{$homePhone}',''),HomePhone),
City = IsNull(NULLIF('{$city}',''), City),
State = IsNull(NULLIF('{$state}',''),State),
Zip = IsNull(NULLIF('{$zip}',''),Zip),
DateOfChangeRequest = '{$date}'
WHERE Clock = '{$username}';
IF (##ROWCOUNT = 0)
BEGIN
IF (NOT EXISTS( SELECT * FROM PendingProcessing WHERE Clock = '{$username}' ))
BEGIN
INSERT INTO PendingProcessing
(
Clock,
Street1,
Street2,
Email,
CellPhone,
HomePhone,
City,
State,
Zip,
DateOfChangeRequest
)
VALUES
(
'{$username}',
'{$addr1}',
'{$addr2}',
'{$email}',
'{$cellPhone}',
'{$homePhone}',
'{$city}',
'{$state}',
'{$zip}',
'{$date}'
);
END;
END;
But the problem is that if there is an address in the Street1 column when a phone number comes in it only leaves the first character in Street1.
The short way is to make the user enter their new address again when entering their new phone number because the first address update was still pending processing. I would prefer to make the code do the extra work though.
So, my question is how can I update columns only when I have data to update them with? I don't want to null existing data, but I also don't want to not update something that has data, say the user entered their new phone number and realized after saving that they had made a typo and needed to change that number.
Thanks for your help.

Related

How to only pull data from table 1 if table 2 also have data

My problem is, I have two tables that we are using for shipping and this is what is happening. If ca.addr_1 has data is fine but if there is data in c.addr_2 then show it. And what I want is if ca.addr has the data on some line use it but if all lines are null then use c.addr.
CO.SHIP_TO_ADDR_NO AS Addr_No,
ISNULL(CA.NAME, C.NAME) AS Name,
ISNULL(CA.ADDR_1, C.ADDR_1) AS Addr_1,
ISNULL(CA.ADDR_2, C.ADDR_2) AS Addr_2,
ISNULL(CA.ADDR_3, C.ADDR_3) AS Addr_3,
ISNULL(CA.CITY, C.CITY) AS City,
ISNULL(CA.STATE, C.STATE) AS State,
ISNULL(CA.ZIPCODE, C.ZIPCODE) AS ZipCode,
ISNULL(CA.COUNTRY, C.COUNTRY) AS Country,
CASE WHEN should allow you to do what you need.
CASE WHEN ca.addr1 IS NULL AND CA.ADDR_2 IS NULL AND CA.ADDR_3 IS NULL
THEN c.addr
ELSE WHEN ....
You can add in as many variations using ELSE WHEN as you need to account for whatever permutation of address results you want to select.

How To Use The Where & Like Operator Together in SQL?

I want to display a List of Instructors with only first name and last name, from Georgia and whose last name ends in ‘son’.
I have written this so far:
SELECT firstname, lastname, state
FROM instructors
WHERE state = 'ga'
AND lastname LIKE '%son'
But it is not returning the information requested just a blank table.
Any help would be greatly appreciated
To find names ending in 'son' you need to make a small change and remove the second '%' sign. with both it looks for 'son' any where such as 'sonnentag'
The second one I would guess that the DB has Georgia as 'GA' not 'ga'. Case is important.
SELECT firstname, lastname, state
FROM instructors
WHERE state = 'GA'
AND lastname LIKE '*son'
This is a formatted comment that shows you how to troubleshoot. Start with this:
SELECT firstname, lastname, state
FROM instructors
WHERE 1 = 1
-- and state = 'ga'
--AND lastname LIKE '%son'
If that returns no records, you have no data. If it does, uncomment the two other filters, one at a time, to see which one causes no records to be returned. It could well be that you simply have no matching records
FINALLY !!!!!
I Figured It Out!
SELECT firstname, lastname, state
FROM instructors
WHERE state = 'ga'
AND lastname LIKE '*son*'
Instead of using the %WildCard I inserted *WildCard on both ends and it displayed exactly what I was requesting !
Thanks Everyone For Your Help!
This should works to you.
SELECT [firstname],[Lastname],[state]
FROM instructors AS i
WHERE i.state = 'ga' AND i.lastname LIKE '%son'

SQL for Splitting Names - Some with Middle Initial, Some Without

I'm fairly new to SQL, I'm actually just building a small database in Access right now although if there is necessary functionality that Access can't do I'll remake the tables in SQL Server.
Here's my situation, I have a list of names that come from a data dump from a third party. In our database I need to be able to compare first and last names in separate columns.
I've been trying to use InStr, Left and Right - but am getting hung up with weird results
Left([NewClaims]![Claimant Full Name],InStr([NewClaims]![Claimant Full Name],",")-1) AS LastName,
Right([NewClaims]![Claimant Full Name],InStr([NewClaims]![Claimant Full Name], ", ")+2) AS FirstName,
On some names it works perfectly
West, Krystal --becomes--> LastName = West, FirstName= Krystal
On other names, similar in formant it doesn't work
Dalton, Kathy ----> LastName = Dalton, First Name = ON, KATHY
On Names with middle initials I get
Earles, Barbara A. ----> LastName = Earles, FirstName= ARBARA A. (one missing letter)
OR
Beard, Chekitha G. ----> LastName = Beard, FirstName= KITHA G. (three missing letters)
I'm frustrated. Can anyone offer another idea on how to make this work? I seem to have the last name down, but I can't get the first name to be consistently correct.
Try this. But I'm assuming that there's always a comma that separates last name from first name.
select
txt,
LastName = left(txt,charindex(',',txt)-1),
FirstName = ltrim(right(txt,len(txt)-charindex(',',txt)))
from (
select 'West, Krystal' as txt union all
select 'Dalton, Kathy' union all
select 'Earles, Barbara A.' union all
select 'Beard, Chekitha G.'
) x
Your mistake was that when using right to extract first name, you didn't take the length of the string under consideration.

Sql for distinct record comparison

I am comparing a table to itself trying to determine whether an email in one record is being used in any one of four other columns in another record.
To make this easier, lets look at an example (simplified):
Name: Bob
Office Email: bob#aaa.com
Home Email: bob#home.com
Mobile Email: bobster#gmail.com
.
Name: Rob
Office Email: rob#bbb.com
Home Email: bob#home.com
Mobile Email: robert#gmail.com
Now I have a sql statement like this:
select c1.ContactId id1, c1.FullName Name1, 'Office Email 1' EmailType1, c1.EMailAddress1 Email,
c2.ContactId id2, c2.FullName Name2,
CASE c1.EmailAddress1
WHEN c2.EMailAddress1 THEN 'Office Email 1'
WHEN c2.Si_OfficeEmail2nd THEN 'Office Email 2'
WHEN c2.EMailAddress2 THEN 'Mobile Email'
WHEN c2.pc_hmemail THEN 'Home Email'
ELSE '?'
END EmailType2,
CASE c1.EmailAddress1
WHEN c2.EMailAddress1 THEN c2.EMailAddress1
WHEN c2.Si_OfficeEmail2nd THEN c2.Si_OfficeEmail2nd
WHEN c2.EMailAddress2 THEN c2.EMailAddress2
WHEN c2.pc_hmemail THEN c2.pc_hmemail
ELSE '?'
END DuplicateEmail
from Contact c1, Contact c2
where (
LTRIM(RTRIM(c1.EMailAddress1 )) = LTRIM(RTRIM(c2.EMailAddress1))
Or LTRIM(RTRIM(c1.EMailAddress1 )) = LTRIM(RTRIM(c2.EMailAddress2))
Or LTRIM(RTRIM(c1.EMailAddress1 )) = LTRIM(RTRIM(c2.pc_hmemail))
Or LTRIM(RTRIM(c1.EMailAddress1 )) = LTRIM(RTRIM(c2.Si_OfficeEmail2nd))
)
And c1.ContactId <> c2.ContactId
And c1.StateCode = 0
and c2.StateCode = 0
order by c1.FullName, c2.FullName
Unfortunately, because Bob and Rob have the same email 'type' (Home Email) that is duplicated due to a typo, my query returns two records, one which shows that Bobs email is duplicated in Robs email, and a second that Robs email is duplicated in Bobs email.
I only need one record. I'm sure this is a common problem but I don't quite know how to describe this problem well enough to have a search engine return something useful.
Perhaps there is a better way of going about this? If not, other than jumping through a bunch of intermediate temporary tables to eliminate these equivalent records, is there a way to write a single query for this?
The solution to your problem is to add the condition: c1.contactId < c2.ContactId. This limits the pairs you are looking at.
If you are looking at emails, you might find a faster approach to look directly at emails. Something like the following will return all emails (on separate rows) that are duplicated:
select e.*
from (select e.*, COUNT(*) over (partition by email) as NumTimes
from ((select contactId, 'Office' as which, EmailAddress1 as email
from Contact
) union all
(select contactId, 'Office2', Si_OfficeEmail2nd
from Contact
) union all
(select contact_id, 'Home', pc_hmemail
from Contact
) union all
(select contact_id, 'Mobile', EmailAddress2
from Contact
)
) e
where email is not null and email <> ''
) e
where NumTimes > 1
order by email
I'd first suggest to continue to normalise your datastructure. A person may have several types of contact information. Therefore the personID, typeID and value can be placed into another table. From this table you can create another relation with a type table, where you keep track of the different contact types (e.g. Home E-mail, Work e-mail, Twitter, linkedIn, Facebook etc). It does not only improve the extendibility of your system but also enables to run these types of queries much more efficiently.
SELECT user.username FROM user u LEFT JOIN contactinfo ci ON u.user_id=ci.user_id LEFT JOIN contacttype ct ON ci.type_id=ct.type_id GROUP BY ci.value HAVING count(value)>1 would be the query to find any duplicate source

How to loop over a list of items of a table in sql

i am new in sql and i want that , i have a table Customer
in which i added a new field Region now i want to do some
alteration in SQL . I want to get all records Customerand check on each
// This check will perfome for every customer let suppose we have our first customer
if currentcustomer.Country = 'US'
{
UPDATE currentcustomer SET currentcustomer.Region=currentcustomer.id
}
else
{
UPDATE currentcustomer SET currentcustomer.Region=currentcustomer.ZIP
}
this is what i want to do but i dont know that how to do this over all customers and how to do this in sql . Please Help me Thanks!!!
UPDATE Customer SET Region='AA'
WHERE Country = 'US'
UPDATE Customer SET Region='ZZ'
WHERE Country <> 'US'
Avoid looping within SQL - it is not designed for looping.
Try to formulate your requirements in set based terminology (I need to update all customers who's country is US to have region AA and all others to region ZZ).
Update:
Seeing your edit, and assuming it is sensible (compatible data types and meaningful data):
UPDATE Customer SET Region= id
WHERE Country = 'US'
UPDATE Customer SET Region= Zip
WHERE Country <> 'US'