Search code examples
t-sqluser-defined-functionszipcode

TSQL Function to find a county based on city and zip


I have a table that has city, state, zip, county and a createdate. I need to have a function that gives me the county name based on the city and zip input where the createdate less than 1/1/2012. What I started with is this:

    ALTER FUNCTION dbo.fn_GetDefaultCounty (
@zip INT,
@city VARCHAR(25)
)
    RETURNS VARCHAR(25)
    AS
    BEGIN

DECLARE @county VARCHAR(25)

SELECT @county = county
FROM tzprod.plandata_rpt.dbo.zipcode
WHERE createdate < '1/1/2012'

RETURN @county
    END

But it's not working. Any help would be appreciated.


Solution

  • You didn't include the input (ZIP, City).

    SELECT @county = county
    FROM tzprod.plandata_rpt.dbo.zipcode
    WHERE zip = @zip AND 
        city = @city AND
        createdate < '1/1/2012'