I know there are lot of similar questions and I went through about 20 of them looking for an answer. Most set a single variable, or used the AND/OR format that I currently have.
I am trying to create a function where I pass in a combination of City, State, Zip and Country and it locates and returns all information. If I use the OR method the first option will return results if Zip and Country are NOT NULL, but then the option where only Zip is NOT NULL could also return a result. These are in the order I want them evaluated (top to bottom). I'm only retuning one value, but I can't guarantee that the results are in the same order, so I'd like to eliminate redundant results.
Here is my current query:
SELECT TOP(1) City, State_abbr, State_long, Zip, Country, County, Longitude, Latitude
FROM [ULTRA].[dbo].[CityStateInfo]
WHERE
( -- Zip Code, Country: Will find City and State /* BEST RESULTS */
@inZip IS NOT NULL AND
@inCountry IS NOT NULL
AND
Zip = @inZip AND
Country = @inCountry
)
OR
( -- City, State, Country: Will find first Zip Code in City, State
@inCity IS NOT NULL AND
@inState IS NOT NULL AND
@inCountry IS NOT NULL
AND
City = @inCity AND
(State_abbr = @inState OR State_long = @inState) AND
Country = @inCountry
)
OR
( -- City, State: Will find first Zip Code in City, State. Will find Country
@inCity IS NOT NULL AND
@inState IS NOT NULL
AND
City = @inCity AND
(State_abbr = @inState OR State_long = @inState)
)
OR
( -- City, State, Zip: Will find Country
@inState IS NOT NULL AND
@inCountry IS NOT NULL
AND
(State_abbr = @inState AND State_long = @inState) AND
Country = @inCountry
)
OR
( -- City, Zip: Will find State and Country
@inCity IS NOT NULL AND
@inState IS NOT NULL
AND
City = @inCity AND
(State_abbr = @inState AND State_long = @inState)
)
OR
( -- State, Zip: Will find City and Country
@inCity IS NOT NULL AND
@inCountry IS NOT NULL
AND
City = @inCity AND
Country = @inCountry
)
OR
(
-- Zip Code: Will find City, State and Country ** Possible error if Country is not US or Canada
@inZip IS NOT NULL
AND
Zip = @inZip
)
This is what I tried with CASE
SELECT TOP(1) City, State_abbr, State_long, Zip, Country, County, Longitude, Latitude
FROM [ULTRA].[dbo].[CityStateInfo]
WHERE
CASE
-- Zip Code, Country: Will find City and State /* BEST RESULTS */
WHEN ( @inZip IS NOT NULL AND @inCountry IS NOT NULL )
THEN Zip = @inZip AND Country = @inCountry
-- City, State, Country: Will find first Zip Code in City, State
WHEN ( @inCity IS NOT NULL AND @inState IS NOT NULL AND @inCountry IS NOT NULL )
THEN City = @inCity AND (State_abbr = @inState OR State_long = @inState) AND Country = @inCountry
END
I received
Incorrect syntax near '='.
which corresponds to the = in "THEN Zip = @inZip AND Country = @inCountry
.
If using the CASE isn't possible, is it possible to do something different with my OR statements to achieve what I'm looking for?
- MS SQL Server v15.0.2070
- SSMS v18.5