I'm trying to replace NULL with a default value of 'NO' but even when I execute it, it still displays NULL when I try to view the data. I've already tried dropping the constraint on the column, but it did not work
/*------------------------
use AuntieB
--alter table charity
-- add STORE char(10);
--update charity
--set STORE = 'YES'
--where Name = 'Salvation Army' or Name = 'Mother Wattles' or Name = 'Fresh Start Charity'
alter table charity
add default 'No' for STORE;
select * from charity
------------------------*/
CharityID Name Address City State Zip Phone ContactID STORE
----------- -------------------- ------------------------------ ------------------------------ ----- ---------- ------------ ----------- ----------
1000 St. Francis Home 45875 West. Hill St. Utica MI 48045 586-795-3486 1025 NULL
1001 Helping Hands 98563 Stadium Detriot MI 48026 313-978-6589 1030 NULL
1002 Boy Scouts 1155 E. Long Lake Rd Troy MI 48085 248-253-9596 1036 NULL
1003 Focus Hope 54362 Grand River Detroit MI 48312 313-478-7895 1041 NULL
1004 Fresh Start Charity 12569 Gratiot Ave. Roseville MI 48084 555-555-2035 1046 YES
1005 St. John Hospital 59652 Shelby Rd. Shelby Twp. MI 48317 586-569-6987 1050 NULL
1006 Salvation Army 56231 Somewhere Blvd. Eastpointe MI 48021 586-555-1212 1056 YES
1007 LA Angels Traders 2468 Halo Park Dr South Los Angelas MI 90234 903-965-3556 2015 NULL
1008 Purple Heart 28765 Van Dyke Sterling Heights MI 48313 586-732-8723 1061 NULL
1009 St. Raja Home 45875 West. Hill St. Utica MI 48045 586-795-3486 1062 NULL
1010 Mother Wattles 4568 Griswold Detroit MI 48205 313-478-9856 2016 YES
1011 Ron McDonald House 649 West Road Utica MI 48045 586-795-9979 1030 NULL
1012 St. Jude 262 Danny Thomas Place Memphis MI 38105 800-822-6344 1030 NULL
(13 rows affected)
From the docs:
When a DEFAULT definition is added to an existing column in a table, by default, the Database Engine applies the new default only to new rows of data that are added to the table. Existing data that was inserted by using the previous DEFAULT definition is unaffected. However, when you add a new column to an existing table, you can specify that the Database Engine insert the default value (specified by the DEFAULT definition) instead of a null value, into the new column for the existing rows in the table.
So when adding a DEFAULT definition to an existing column, you need to fill the existing rows yourself.
You cannot add a new default constraint to an existing column and update exiting NULL values in the same DDL operation. You'll need to explicitly update values NULL values to the desired value afterward.
You can, however, add a new column with a default constraint and apply the default value to all existing rows by specifying the WITH VALUES clause:
ALTER TABLE dbo.charity
ADD store char(10) NULL
CONSTRAINT df_charity_STORE DEFAULT 'No'
WITH VALUES;
This method allows you to add a new NOT NULL column too.
If you are running Enterprise (or Developer) edition of SQL Server, WITH VALUES is a meta-data only operation, which avoids updating every row in the table internally during the operation. The operation physically updates each row in the table in lessor editions.
There are two options here. You can update all null values like this;
update charity
set STORE = 'NO'
where STORE is null
or If you want to replace null values only when selecting them, you can use ISNULL statement.
select ISNULL(STORE,'NO') from charity
Also, adding constraint with default value for existing column doesn't update previous data. It sets default value for new coming rows.
I have to compare addresses from two tables and get the Id if the address matches.
Each table has three columns Houseno, street, state
The address are not in standard format in either of the tables. There are approx. 50,000 rows, I need to scan through
At some places its Ave. Avenue Ave . Str Street, ST. Lane Ln. Place PL Cir CIRCLE.
Any combination with a dot or comma or spaces ,hypen.
I was thinking of combining all three What can be best way to do it in SQL or PLSQL for example
table1
HNO STR State
----- ----- -----
12 6th Ave NY
10 3rd Aven SD
12-11 Fouth St NJ
11 sixth Lane NY
A23 Main Parkway NY
A-21 124 th Str. VA
table2
id HNO STR state
-- ----- ----- -----
1 12 6 Ave. NY
13 10 3 Avenue SD
15 1121 Fouth Street NJ
33 23 9th Lane NY
24 X23 Main Cir. NY
34 A1 124th Street VA
There is no simple way to achieve what you want. There is a expensive software (google for "address standardization software") that can do this but rarely 100% automatic.
What this type of software does is to take the data, use complex heuristics to try to figure out the "official" address and then return that (sometimes with the confidence that the result is correct, sometimes a list of results sorted by confidence).
For a small percentage of the data, the software will simply not work and you'll have to fix that yourself.
Oracle has a built in package UTL_Match which has an edit_distance function (based on the Levenshtein algorithm, this is a measure of how many changes you would need to make to make one string the same as another). More info about this Package / Function can be found here: http://docs.oracle.com/cd/E18283_01/appdev.112/e16760/u_match.htm
You would need to make some decisions around whether to compare each column or concatenate and then compare and what a reasonable threshold is. For example, you may want to do a manual check on any with an edit distance of less than 8 on the concatenated values.
Let me know if you want any help with the syntax, the edit_distance function just takes 2 varchar2 args (the strings you want to compare) and returns a number.
This is not a perfect solution in that if you set the threshold high you will have a lot of manual checking to do to discard some, and if you set it too low you will miss some matches, but it may be about the best if you want a relatively simple solution.
The way we did this for one of our applications was to use a third party adddress normalization API(eg:Pitney Bowes),normalize each address(Address is a combination of Street Address,City ,State and Zip) and create a T-sql hash for that address.For the adress to compare do the same thing and compare the two hashes and if they match,we have a match
you can make a cursor where you do first a group by where house number and city =.
in a loop
you can separate a row with instr e substr considering chr(32).
After that you can try to consider to make a confront with substring where you have a number 6 = 6th , other case street = str.
good luck!
I have an address column that contains address, state and postcode. I would like to extract the address, suburb, state, and postcode into separate columns, how can a do this as the length of the address is variable, there is a ^ to separate the address and "other" details. The State can be 2 or 3 characters long and the postcode is always 4 characters long.
PostalAddress TO BE Address Suburb State Postcode
28 Smith Avenue^MOOROOLBARK VIC 3138^ 28 Smith Avenue MOOROOLBARK VIC 3138
16 Farr Street^HEYFIELD VIC 3858^ 16 Farr Street HEYFIELD VIC 3858
17 Terry Road^LOWER PLENTY VIC 3093^ 17 Terry Road LOWER PLENTY VIC 3093
String parsing in SQL is messy and tends to be brittle. I usually think it's best to do these sort of tasks outside of SQL altogether. That said, given the mini-spec above, it is possible to parse the data into the fields you want like so:
select
left(PostalAddress, charindex('^', PostalAddress) - 1) as street_address,
left(second_part, len(second_part) - charindex(' ', reverse(second_part))) as suburb,
right(second_part, charindex(' ', reverse(second_part))) as state,
reverse(substring(reverse(PostalAddress), 2, 4)) as postal_code
from (
select
PostalAddress,
rtrim(reverse(substring(reverse(PostalAddress), 6, len(PostalAddress) - charindex('^', PostalAddress) - 5))) as second_part
from Addresses
) as t1
Note that you'll need so substitute your table name for what I've called addresses in the subquery above.
You can see this in action against your sample data here.
In my case it's just to get a five-numeric from a string as a postcode:
Below is my code:
Select SUBSTRING([Column or string],patindex('%[0-9][0-9][0-9][0-9][0-9]%',[Column or string]),5) AS 'Postcode'
Where can I find a list of the US States in a form for importing into my database?
SQL would be ideal, otherwise CSV or some other flat file format is fine.
Edit: Complete with the two letter state codes
I needed this a few weeks ago and put it on my blog as SQL and Tab Delimited. The data was sourced from wikipedia in early January so should be up to date.
US States: http://www.john.geek.nz/index.php/2009/01/sql-tips-list-of-us-states/
I use the Worlds Simplest Code Generator if I need to add columns or remove some of the fields - http://secretgeek.net/wscg.asp
I've also done Countries of the world and International Dialling Codes too.
Countries: http://www.john.geek.nz/index.php/2009/01/sql-tips-list-of-countries/
IDC's: http://www.john.geek.nz/index.php/2009/01/sql-tips-list-of-international-dialling-codes-idcs/
Edit: New: Towns and cities of New Zealand
Depending on why you need the states, it is worth keeping in mind that there are more than 50 valid state codes. For someone deployed outside the USA, it is annoying to come across websites that do not allow address entry with perfectly valid state codes like AE and AP. A better resource would be USPS.
Cut/Paste these into notepad and then import..should be easy enough - there are only 50 after all:
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming
Out of interest: As there are only 50 and they rarely change, couldn't you not just manually create such a list from a source and put it on a public webspace?
In response to #cspoe7's astute observation, here is a query with all valid states and their abbreviations according to USPS. I have them sorted here by category (official US states, District of Columbia, US territories, military "states") and then alphabetically.
INSERT INTO State (Name, Abbreviation)
VALUES
('Alabama','AL'), -- States
('Alaska','AK'),
('Arizona','AZ'),
('Arkansas','AR'),
('California','CA'),
('Colorado','CO'),
('Connecticut','CT'),
('Delaware','DE'),
('Florida','FL'),
('Georgia','GA'),
('Hawaii','HI'),
('Idaho','ID'),
('Illinois','IL'),
('Indiana','IN'),
('Iowa','IA'),
('Kansas','KS'),
('Kentucky','KY'),
('Louisiana','LA'),
('Maine','ME'),
('Maryland','MD'),
('Massachusetts','MA'),
('Michigan','MI'),
('Minnesota','MN'),
('Mississippi','MS'),
('Missouri','MO'),
('Montana','MT'),
('Nebraska','NE'),
('Nevada','NV'),
('New Hampshire','NH'),
('New Jersey','NJ'),
('New Mexico','NM'),
('New York','NY'),
('North Carolina','NC'),
('North Dakota','ND'),
('Ohio','OH'),
('Oklahoma','OK'),
('Oregon','OR'),
('Pennsylvania','PA'),
('Rhode Island','RI'),
('South Carolina','SC'),
('South Dakota','SD'),
('Tennessee','TN'),
('Texas','TX'),
('Utah','UT'),
('Vermont','VT'),
('Virginia','VA'),
('Washington','WA'),
('West Virginia','WV'),
('Wisconsin','WI'),
('Wyoming','WY'),
('District of Columbia','DC'),
('American Samoa','AS'), -- Territories
('Federated States of Micronesia','FM'),
('Marshall Islands','MH'),
('Northern Mariana Islands','MP'),
('Palau','PW'),
('Puerto Rico','PR'),
('Virgin Islands','VI'),
('Armed Forces Africa','AE'), -- Armed Forces
('Armed Forces Americas','AA'),
('Armed Forces Canada','AE'),
('Armed Forces Europe','AE'),
('Armed Forces Middle East','AE'),
('Armed Forces Pacific','AP')
If you need to memorize them, let Wakko help you :)
You can download a lot of lists on http://www.freebase.com/ .
http://www.geonames.org/export/
The GeoNames geographical database is available for download free of charge under a creative commons attribution license. It contains over eight million geographical names and consists of 6.5 million unique features whereof 2.2 million populated places and 1.8 million alternate names. All features are categorized into one out of nine feature classes and further subcategorized into one out of 645 feature codes. (more statistics ...).
The data is accessible free of charge through a number of webservices and a daily database export.
You could use google sets to make a list of all states as well as lists of more or less anything.
If you need only 52 states SQL server script you can use the following query: solved
INSERT INTO
States ( StateName )
VALUES
( 'Alabama'),
( 'Alaska'),
( 'Arizona'),
( 'Arkansas'),
( 'California'),
( 'Colorado'),
( 'Connecticut'),
( 'Delaware'),
( 'District of Columbia'),
( 'Florida'),
( 'Georgia'),
( 'Hawaii'),
( 'Idaho'),
( 'Illinois'),
( 'Indiana'),
( 'Iowa'),
( 'Kansas'),
( 'Kentucky'),
( 'Louisiana'),
( 'Maine'),
( 'Maryland'),
( 'Massachusetts'),
( 'Michigan'),
( 'Minnesota'),
( 'Mississippi'),
( 'Missouri'),
( 'Montana'),
( 'Nebraska'),
( 'Nevada'),
( 'New Hampshire'),
( 'New Jersey'),
( 'New Mexico'),
( 'New York'),
( 'North Carolina'),
( 'North Dakota'),
( 'Ohio'),
( 'Oklahoma'),
( 'Oregon'),
( 'Pennsylvania'),
( 'Puerto Rico'),
( 'Rhode Island'),
( 'South Carolina'),
( 'South Dakota'),
( 'Tennessee'),
( 'Texas'),
( 'Utah'),
( 'Vermont'),
( 'Virginia'),
( 'Washington'),
( 'West Virginia'),
( 'Wisconsin'),
( 'Wyoming');
I'm just gonna put this list of the United States bash/linux format here so I can save someone some time:
alabama|alaska|arizona|arkansas|california|colorado|connecticut|delaware|florida|georgia|hawaii|idaho|illinois|indiana|iowa|kansas|kentucky|louisiana|maine|maryland|massachusetts|michigan|minnesota|mississippi|missouri|montana|nebraska|nevada|newhampshire|newjersey|newmexico|newyork|northcarolina|northdakota|ohio|oklahoma|oregon|pennsylvania|rhodeisland|southcarolina|southdakota|tennessee|texas|utah|vermont|virginia|washington|westvirginia|wisconsin|wyoming