I am trying to convert this to a stored procedure in SQL Server from an ASP script. I have tried to follow the procedures outlined at http://www.sommarskog.se/dyn-search.html, but due to lack of understanding; I can't figure out what is needed to create the search string. Once I can figure that out, then I can attach the string to the rest of the dynamic sql. I have the list to table function, and the intList_tabletype defined in the database, as well as the rest of the SP. The searchArr variable can be one keyword, a delimited list of keywords or a phrase. Any help will be greatly appreciated. Thanks
'SQL - Keywords
If Len(strSearch) > 0 Then
'Create array of keywords. If we're doing a PHRase
'search, an array with only one position is created
'containing the entire search string. If an AND or
'an OR "keyword" search is being performed, each word
'is put into it's own array position.
If strSearchType = "PHR" Then
searchArr(0) = Trim(strSearch)
Else
searchArr = strSearch.Split(" "c)
End If
'Keyword search SQL
tmpSQL1 = "(Brewery.BreweryName LIKE "
tmpSQL2 = "(Products.description LIKE "
tmpSQL3 = "(Products.Notes LIKE "
tmpSQL4 = "(Products.SKU LIKE "
For i = 0 To UBound(searchArr)
If i = UBound(searchArr) Then
tmpSQL1 = tmpSQL1 & "'%" & searchArr(i) & "%')"
tmpSQL2 = tmpSQL2 & "'%" & searchArr(i) & "%')"
tmpSQL3 = tmpSQL3 & "'%" & searchArr(i) & "%')"
tmpSQL4 = tmpSQL4 & "'%" & searchArr(i) & "%')"
Else
tmpSQL1 = tmpSQL1 & "'%" & searchArr(i) & "%' " & strSearchType & " Brewery.BreweryName LIKE "
tmpSQL2 = tmpSQL2 & "'%" & searchArr(i) & "%' " & strSearchType & " Products.description LIKE "
tmpSQL3 = tmpSQL3 & "'%" & searchArr(i) & "%' " & strSearchType & " Products.Notes LIKE "
tmpSQL4 = tmpSQL4 & "'%" & searchArr(i) & "%' " & strSearchType & " Products.SKU LIKE "
End If
Next
'Put it all together
searchSQL = searchSQL & "AND (" & tmpSQL1 & " OR " & tmpSQL2 & " OR " & tmpSQL3 & " OR " & tmpSQL4 & ") "
End If
When i run this script on the web page, I get this string.
Single keyword Or Phrase
AND ((Brewery.BreweryName LIKE '%Bud%') OR (Products.description LIKE '%Bud%') OR (Products.Notes LIKE '%Bud%') OR (Products.SKU LIKE '%Bud%') OR (Brands.Brand LIKE '%Bud%'))
Multiple Keywords
AND ((Brewery.BreweryName LIKE '%Bud%' OR Brewery.BreweryName LIKE '%Busch%') OR (Products.description LIKE '%Bud%' OR Products.description LIKE '%Busch%') OR (Products.Notes LIKE '%Bud%' OR Products.Notes LIKE '%Busch%') OR (Products.SKU LIKE '%Bud%' OR Products.SKU LIKE '%Busch%') OR (Brands.Brand LIKE '%Bud%' OR Brands.Brand LIKE '%Busch%'))
This is the Procedure I have come up so far.
ALTER PROCEDURE [dbo].[GetProductsBySearch]
#idProduct int = NULL,
#sku nvarchar(20) = NULL,
#breweryname nvarchar(40) = NULL,
#brand nvarchar(40) = NULL,
#country nvarchar(15) = NULL,
#prodname nvarchar(40) = NULL,
#searchStr nvarchar(MAX) = NULL,
--#PHRtbl intlist_tbltype READONLY,
#sortExpression nvarchar(50) = NULL,
#startRowIndex int,
#maximumRows int,
#idLocation int = NULL,
#idBrand int = NULL,
#strSearchType nvarchar(5) = ' OR ',
#debug bit = 0
AS
DECLARE #sql nvarchar(MAX),
#paramlist nvarchar(4000),
#nl char(2) = char(13) + char(10)
DECLARE #PHRtbl TABLE
( PK INT IDENTITY(1,1) PRIMARY KEY,
item NVARCHAR (MAX)
)
IF #sortExpression IS NULL
SET #sortExpression = 'sku'
INSERT INTO #PHRtbl
SELECT item FROM [dbo].[udf_List2Table](#searchStr,',')
DECLARE #i INT
SELECT #i = MIN(PK) FROM #PHRtbl
DECLARE #max INT
SELECT #max = MAX(PK) FROM #PHRtbl
DECLARE #SearchSQL AS NVARCHAR(MAX) = ''
DECLARE #item AS NVARCHAR(MAX) = NULL
DECLARE #tmpSQL1 AS NVARCHAR(MAX) = '(Brewery.BreweryName LIKE '
DECLARE #tmpSQL2 AS NVARCHAR(MAX) = '(Products.description LIKE '
DECLARE #tmpSQL3 AS NVARCHAR(MAX) = '(Products.Notes LIKE '
DECLARE #tmpSQL4 AS NVARCHAR(MAX) = '(Products.SKU LIKE '
DECLARE #tmpSQL5 AS NVARCHAR(MAX) = '(Brands.Brand LIKE '
SELECT #sql =
'SELECT SKU, productName, imgUrlThumb, Size, ProdType, CanType,
CanManufacturer, breweryName, locName, CountryFlag, Brand
FROM
(SELECT Products.SKU, Products.Description as productName, Products.imgUrlThumb, LookupSize.Size, ProdType.ProdType, CanTypes.Description AS CanType,
CanManufacturer.CanManufacturer, brewery.breweryName, Locations.locName, Locations.CountryFlag, Brands.Brand,
ROW_NUMBER() OVER(ORDER BY ' + #sortExpression + ') AS RowNum
FROM Products INNER JOIN
brewery ON Products.idBrewery = brewery.idBrewery INNER JOIN
CanManufacturer ON Products.idCanManufacturer = CanManufacturer.idCanManufacturer INNER JOIN
CanTypes ON Products.idCanType = CanTypes.idCanType INNER JOIN
Locations ON brewery.idLocation = Locations.idLocation INNER JOIN
LookupSize ON Products.idSize = LookupSize.idSize INNER JOIN
ProdType ON Products.idProdType = ProdType.idProdtype INNER JOIN
CatProd ON Products.idProduct = CatProd.idProduct INNER JOIN
Categories ON CatProd.idCategory = Categories.idCategory INNER JOIN
Brands ON Brands.idBrand = Products.idBrand
WHERE 1 = 1 ' + #nl
IF #searchStr IS NOT NULL
WHILE #i <= #max
BEGIN
SELECT #item = item FROM #PHRtbl WHERE PK = #i
IF (#i = #max)
BEGIN
SET #tmpSQL1 += ''%'' & #item + ''%')'
SET #tmpSQL2 += ''%'' & #item + ''%')'
SET #tmpSQL3 += ''%'' & #item + ''%')'
SET #tmpSQL4 += ''%'' & #item + ''%')'
SET #tmpSQL5 += ''%'' & #item + ''%')'
END
ELSE
BEGIN
SET #tmpSQL1 += ''%'' & #item + ''%')' + #strSearchType + ' Brewery.BreweryName LIKE '
SET #tmpSQL2 += ''%'' & #item + ''%')' + #strSearchType + ' Products.description LIKE '
SET #tmpSQL3 += ''%'' & #item + ''%')' + #strSearchType + ' Products.Notes LIKE '
SET #tmpSQL4 += ''%'' & #item + ''%')' + #strSearchType + ' Products.SKU LIKE '
SET #tmpSQL5 += ''%'' & #item + ''%')' + #strSearchType + ' Brands.Brand LIKE '
END
SELECT #item = NULL
SET #i = #i + 1
END
--moved this out of the while loop
-- put it all together
SET #SearchSQL = #SearchSQL + 'AND (' + #tmpSQL1 + ' OR ' + #tmpSQL2 + ' OR ' + #tmpSQL3 + ' OR ' + #tmpSQL4 + ' OR ' + #tmpSQL5 + ') ' + #nl
-- Uncommend below to check the SQL
PRINT #SearchSQL
SELECT #sql += ' #SearchSQL' + #nl
IF #idProduct IS NOT NULL
SELECT #sql += ' AND Products.idProduct = #idProduct' + #nl
IF #idBrand IS NOT NULL
SELECT #sql += ' AND Products.idBrand = #idBrand' + #nl
IF #idLocation IS NOT NULL
SELECT #sql += ' AND Brewery.idLocation = #idLocation' + #nl
IF #brand IS NOT NULL
SELECT #sql += ' AND Brands.brand LIKE ''%'' + #brand + ''%''' + #nl
IF #breweryname IS NOT NULL
SELECT #sql += ' AND Brewery.breweryName LIKE ''%'' + #breweryname + ''%''' + #nl
IF #prodname IS NOT NULL
SELECT #sql += ' AND Products.Description LIKE ''%'' + #prodname + ''%''' + #nl
IF #searchStr IS NOT NULL
SELECT #sql += ' #searchStr' + #nl
SELECT #sql += ') AS myData
WHERE RowNum BETWEEN (' + CONVERT(nvarchar(10), #startRowIndex) +
' - 1) * ' + CONVERT(nvarchar(10),#MaximumRows) + ' AND (((' + CONVERT(nvarchar(10), #startRowIndex) + ' - 1) * '
+ CONVERT(nvarchar(10), #maximumRows) + ' + 1) + ' + CONVERT(nvarchar(10), #maximumRows) + ') - 1'
--IF EXISTS (SELECT * FROM #PHRtbl)
-- SELECT #sql += ' AND o.EmployeeID IN (SELECT val FROM #employeetbl)' + #nl
--SELECT #sql += ' ORDER BY o.OrderID' + #nl
IF #debug = 1
PRINT #sql
SELECT #paramlist = '#idProduct int,
#sku nvarchar(20) ,
#breweryname nvarchar(40) ,
#brand nvarchar(40) ,
#country nvarchar(15) ,
#prodname nvarchar(40) ,
#searchStr nvarchar(MAX) ,
#PHRtbl intlist_tbltype READONLY,
#sortExpression nvarchar(50),
#startRowIndex int,
#maximumRows int,
#idLocation int,
#idBrand int,
#strSearchType nvarchar(5)'
EXEC sp_executesql #sql, #paramlist,
#idProduct,#sku,#breweryname,#brand,#country,#prodname,#searchStr,#PHRtbl,#sortExpression,
#startRowIndex,#maximumRows,#idLocation,#idBrand
Now when I try to execute the procedure I am getting the following errors. Due to the While loop to build the string. Know I have to figure out what is causing the error, and build the string and attach it #SQL that is being built.
**Msg 402, Level 16, State 1, Procedure GetProductsBySearch, Line 75
The data types varchar and varchar are incompatible in the modulo operator.
**
I was able to get the procedure to compile in the database by changing the quotes in this part.
IF (#i = #max)
BEGIN
SET #tmpSQL1 += '''%' + #item + '%'')'
SET #tmpSQL2 += '''%' + #item + '%'')'
SET #tmpSQL3 += '''%' + #item + '%'')'
SET #tmpSQL4 += '''%' + #item + '%'')'
SET #tmpSQL5 += '''%' + #item + '%'')'
END
ELSE
BEGIN
SET #tmpSQL1 += '''%' + #item + '%'')' + #strSearchType + ' Brewery.BreweryName LIKE '
SET #tmpSQL2 += '''%' + #item + '%'')' + #strSearchType + ' Products.description LIKE '
SET #tmpSQL3 += '''%' + #item + '%'')' + #strSearchType + ' Products.Notes LIKE '
SET #tmpSQL4 += '''%' + #item + '%'')' + #strSearchType + ' Products.SKU LIKE '
SET #tmpSQL5 += '''%' + #item + '%'')' + #strSearchType + ' Brands.Brand LIKE '
END
Now when I execute it I get this error.
Msg 206, Level 16, State 2, Line 0
Operand type clash: table is incompatible with nvarchar
I suspect the above section is the culprit. I have a Print Statement to Print the Strings as they are built, the error comes up first. Where or how do I see what the #SearchStr variable looks like?
I have extracted that section of code into a new window. With one value in the searchStr variable I get the the correct build of the searchSQL.
AND ((Brewery.BreweryName LIKE '%Bud%')
OR (Products.description LIKE '%Bud%')
OR (Products.Notes LIKE '%Bud%')
OR (Products.SKU LIKE '%Bud%')
OR (Brands.Brand LIKE '%Bud%')
)
However when I add another item to the list I get this:
AND ((Brewery.BreweryName LIKE '%Bud%') OR Brewery.BreweryName LIKE
OR (Products.description LIKE '%Bud%') OR Products.description LIKE
OR (Products.Notes LIKE '%Bud%') OR Products.Notes LIKE
OR (Products.SKU LIKE '%Bud%') OR Products.SKU LIKE
OR (Brands.Brand LIKE '%Bud%') OR Brands.Brand LIKE
)
I am almost there. Just need to figure what part of the string needs readjusting to get it right
AND ((Brewery.BreweryName LIKE '%Bud%') OR Brewery.BreweryName LIKE
'%Busch%')
OR (Products.description LIKE '%Bud%') OR Products.description LIKE
'%Busch%')
OR (Products.Notes LIKE '%Bud%') OR Products.Notes LIKE
'%Busch%')
OR (Products.SKU LIKE '%Bud%') OR Products.SKU LIKE
'%Busch%')
OR (Brands.Brand LIKE '%Bud%') OR Brands.Brand LIKE
'%Busch%')
)
Background:
We recently had a project where we had to plot Institutions on a Google map however using the address to pinpoint the institution took way to long to load. Therefore we decided to store the lat/lng in the database against the institution record. To get this we created a Stored Procedure usp_web_kam_Geocode that calls the GoogleMaps geocoding service to return the coordinates which are then stored.
We then created a trigger trg_Geocode on tblInstitution after INSERT, UPDATE which providing some conditions were met (bIncludeInKAMMap = 1 i.e. its to be plotted) then it called usp_web_kam_Geocode and updates the coordinates on the record.
Problem:
Once this trigger was added to the table any call to usp_web_InsertUpdateInstitution (responsible for inserting and updating tblInstitution) fails without a error when called from the web app..
We have used SQL Server Profiler to trace this call to usp_web_InsertUpdateInstitution which produced the following:
declare #p1 int
set #p1=149078313
exec usp_web_InsertUpdateInstitution #lInstitutionID=#p1 output,#lRegionID=132,#TOREFMadisunNumber=N'',#sSageNumber=N'',#sName=N'Replication Test Changed',#Xaddress=N'',#sPostCode=N'GU97DR',#sPhone=N'',#sFax=N'',#lInstitutionTypeID=14,#sNote=N'',#lModifiedByID=0,#sAddress1=N'',#sAddress2=N'',#sAddress3=N'',#sTown=N'',#sCounty=N'',#TOREFCountry=N'',#sWebsite=N'',#lDistributorID=2,#XFCRef=0,#sSICCode=N'',#lEmployees=0,#sSource=N'',#bKeyAccount=0,#TOREFProspectType=N'',#sVAddress1=N'',#sVAddress2=N'',#sVAddress3=N'',#sVTown=N'',#sVCounty=N'',#TOREFVCountry=N'',#sVPostcode=N'',#bHasSepticUnit=0,#lBusinessManagerTempID=0,#lProspectTypeID=1,#lGroupID=1,#lCountryID=180,#lVCountryID=-2,#bDeleted=0,#lValueID=NULL,#sGeneralEmail=N'',#lMarketingID=48509669,#sVisitingAddress=N'',#bIsolator=0,#bLAF=0,#bGradeAB=0,#bGradeCD=0,#bUnclassified=0,#bNoProduction=0,#sIsolatorQty=N'',#sLAFQty=N'',#sGradeABArea=N'',#sGradeCDArea=N'',#sUnclassifiedArea=N'',#bIncludeInKAM=1,#fLat=55.378050999999999,#fLong=-3.4359730000000002,#bRespQuality=0,#bRespMicro=0,#bRespPurchasing=0,#bRespValidation=0,#bKindIsolator=0,#bKindRABS=0,#bKindOLA=0,#bKindOLB=0,#bKindOLC=0,#bKindOLD=0,#lNoCleanroomOperatives=0,#sProductsManufactured=N'',#sComments=N'Test wm4',#lValueAlcohol=0,#lValueBiocides=0,#lValueWipes=0,#lValueEquipment=0,#lValueNonSterile=0,#lValueOther=0,#lGeocodeAttempts=6,#sGeocodeLastStatus=N'OK'
select #p1
The first two rows of the screenshot are from the web app (which doesn't work) and the last two are from SSMS (which work correctly)
BUT if we copy the exact SQL from above and run it in SSMS (with the same login as the web app) it works correctly inserting or updating a record and successfully retrieves the lat/lng from the webservice
Code:
Institution.Save()
Public Function Save() As Integer
Dim cn As New SqlConnection(My.Settings.ShieldCRMConnectionString)
Dim cmd As New SqlCommand
Dim strSQL As String = "usp_web_InsertUpdateInstitution"
Try
cn.Open()
cmd.Connection = cn
cmd.CommandText = strSQL
cmd.CommandType = CommandType.StoredProcedure
Dim prmInstitutionID As New SqlParameter
prmInstitutionID.ParameterName = "#lInstitutionID"
prmInstitutionID.Value = intInstitutionID
prmInstitutionID.Direction = ParameterDirection.InputOutput
cmd.Parameters.Add(prmInstitutionID)
'** Parameters clipped out for readability
cmd.ExecuteNonQuery()
Return cmd.Parameters("#lInstitutionID").Value
Catch ex As Exception
Elmah.ErrorSignal.FromCurrentContext.Raise(ex)
Return -1
Finally
cmd.Dispose()
cn.Close()
cn.Dispose()
End Try
trg_Geolocation
ALTER TRIGGER [dbo].[trg_Geolocation] ON [dbo].[tblInstitution] AFTER INSERT, UPDATE
AS
BEGIN
DECLARE #lInstitutionID INT
DECLARE #sAddress1 VARCHAR(500)
DECLARE #sAddress2 VARCHAR(500)
DECLARE #sAddress3 VARCHAR(500)
DECLARE #sTown VARCHAR(500)
DECLARE #sCounty VARCHAR(500)
DECLARE #sPostcode VARCHAR(500)
DECLARE #sCountry VARCHAR(500)
DECLARE #lCountryID INT
DECLARE cur CURSOR FOR
SELECT lInstitutionID,
sAddress1,
sAddress2,
sAddress3,
sTown,
sCounty,
sPostCode,
C.lCountryID,
C.sName AS sCountry
FROM inserted I
INNER JOIN refCountry C ON I.lCountryID = C.lCountryID
WHERE ISNULL(bIncludeInKAM, 0) = 1
OPEN cur
FETCH NEXT FROM cur INTO #lInstitutionID, #sAddress1, #sAddress2, #sAddress3, #sTown, #sCounty, #sPostCode, #lCountryID, #sCountry
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #fLat FLOAT
DECLARE #fLng FLOAT
DECLARE #sAddress VARCHAR(MAX)
DECLARE #sLastStatus VARCHAR(200)
SELECT #fLat = NULL, #fLng = NULL, #sAddress = NULL
SELECT #sAddress =
CASE WHEN REPLACE(REPLACE(ISNULL(#sAddress1 + ', ', '') + ISNULL(#sAddress2 + ', ', '') + ISNULL(#sAddress3 + ', ', '') + ISNULL(#sTown + ', ', '') + ISNULL(#sCounty + ', ', '') + #sCountry, ', , , ', ', '), ', , ', ', ')
LIKE ', %' THEN RIGHT(REPLACE(REPLACE(ISNULL(#sAddress1 + ', ', '') + ISNULL(#sAddress2 + ', ', '') + ISNULL(#sAddress3 + ', ', '') + ISNULL(#sTown + ', ', '') + ISNULL(#sCounty + ', ', '') + #sCountry, ', , , ', ', '), ', , ', ', '),
LEN(REPLACE(REPLACE(ISNULL(#sAddress1 + ', ', '') + ISNULL(#sAddress2 + ', ', '') + ISNULL(#sAddress3 + ', ', '') + ISNULL(#sTown + ', ', '') + ISNULL(#sCounty + ', ', '') + #sCountry, ', , , ', ', '), ', , ', ', ')) - 2)
ELSE REPLACE(REPLACE(ISNULL(#sAddress1 + ', ', '') + ISNULL(#sAddress2 + ', ', '') + ISNULL(#sAddress3 + ', ', '') + ISNULL(#sTown + ', ', '') + ISNULL(#sCounty + ', ', '') + #sCountry, ', , , ', ', '), ', , ', ', ') END
BEGIN TRY
EXEC usp_web_kam_Geocode #sAddress = #sAddress OUTPUT, #fLat = #fLat OUTPUT, #fLng = #fLng OUTPUT, #sGeocodeLastStatus = #sLastStatus OUTPUT
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE()
END CATCH
IF NOT (#fLat IS NULL AND #fLng IS NULL)
BEGIN
UPDATE tblInstitution
SET fLat = #fLat,
fLong = #fLng,
lGeocodeAttempts = ISNULL(lGeocodeAttempts, 0) + 1,
sGeocodeLastStatus = #sLastStatus
WHERE lInstitutionID = #lInstitutionID
END
FETCH NEXT FROM cur INTO #lInstitutionID, #sAddress1, #sAddress2, #sAddress3, #sTown, #sCounty, #sPostCode, #lCountryID, #sCountry
END
CLOSE cur
DEALLOCATE cur
END
usp_web_kam_Geocode
ALTER PROCEDURE [dbo].[usp_web_kam_Geocode]
#sAddress VARCHAR(80) = NULL OUTPUT,
#sCity VARCHAR(40) = NULL OUTPUT,
#sState VARCHAR(40) = NULL OUTPUT,
#sCounty VARCHAR(40) = NULL OUTPUT,
#sCountry VARCHAR(40) = NULL OUTPUT,
#sPostCode VARCHAR(20) = NULL OUTPUT,
#sGeocodeLastStatus VARCHAR(200) = NULL OUTPUT,
#fLat FLOAT = NULL OUTPUT,
#fLng FLOAT = NULL OUTPUT,
#sMapURL VARCHAR(1024) = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #sURL varchar(MAX)
SET #sURL = 'http://maps.google.com/maps/api/geocode/xml?sensor=false&address=' +
CASE WHEN #sAddress IS NOT NULL THEN #sAddress ELSE '' END +
CASE WHEN #sCity IS NOT NULL THEN ', ' + #sCity ELSE '' END +
CASE WHEN #sState IS NOT NULL THEN ', ' + #sState ELSE '' END +
CASE WHEN #sPostCode IS NOT NULL THEN ', ' + #sPostCode ELSE '' END +
CASE WHEN #sCountry IS NOT NULL THEN ', ' + #sCountry ELSE '' END
SET #sURL = REPLACE(#sURL, ' ', '+')
DECLARE #Response varchar(8000)
DECLARE #XML xml
DECLARE #Obj int
DECLARE #Result int
DECLARE #HTTPStatus int
DECLARE #ErrorMsg varchar(MAX)
EXEC #Result = sp_OACreate 'MSXML2.ServerXMLHttp', #Obj OUT
BEGIN TRY
EXEC #Result = sp_OAMethod #Obj, 'open', NULL, 'GET', #sURL, false
EXEC #Result = sp_OAMethod #Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded'
EXEC #Result = sp_OAMethod #Obj, send, NULL, ''
EXEC #Result = sp_OAGetProperty #Obj, 'status', #HTTPStatus OUT
EXEC #Result = sp_OAGetProperty #Obj, 'responseXML.xml', #Response OUT
END TRY
BEGIN CATCH
SET #ErrorMsg = ERROR_MESSAGE()
END CATCH
EXEC #Result = sp_OADestroy #Obj
IF (#ErrorMsg IS NOT NULL) OR (#HTTPStatus <> 200) BEGIN
SET #ErrorMsg = 'Error in Geocode: ' + ISNULL(#ErrorMsg, 'HTTP result is: ' + CAST(#HTTPStatus AS varchar(10)))
RAISERROR(#ErrorMsg, 16, 1, #HTTPStatus)
RETURN
END
SET #XML = CAST(#Response AS XML)
SET #sGeocodeLastStatus = #XML.value('(/GeocodeResponse/status) [1]', 'varchar(200)')
SET #fLat = #XML.value('(/GeocodeResponse/result/geometry/location/lat) [1]', 'numeric(9,6)')
SET #fLng = #XML.value('(/GeocodeResponse/result/geometry/location/lng) [1]', 'numeric(9,6)')
SET #sCity = #XML.value('(/GeocodeResponse/result/address_component[type="locality"]/long_name) [1]', 'varchar(40)')
SET #sState = #XML.value('(/GeocodeResponse/result/address_component[type="administrative_area_level_1"]/short_name) [1]', 'varchar(40)')
SET #sPostCode = #XML.value('(/GeocodeResponse/result/address_component[type="postal_code"]/long_name) [1]', 'varchar(20)')
SET #sCountry = #XML.value('(/GeocodeResponse/result/address_component[type="country"]/short_name) [1]', 'varchar(40)')
SET #sCounty = #XML.value('(/GeocodeResponse/result/address_component[type="administrative_area_level_2"]/short_name) [1]', 'varchar(40)')
SET #sAddress =
ISNULL(#XML.value('(/GeocodeResponse/result/address_component[type="street_number"]/long_name) [1]', 'varchar(40)'), '???') + ' ' +
ISNULL(#XML.value('(/GeocodeResponse/result/address_component[type="route"]/long_name) [1]', 'varchar(40)'), '???')
SET #sMapURL = 'http://maps.google.com/maps?f=q&hl=en&q=' + CAST(#fLat AS varchar(20)) + '+' + CAST(#fLng AS varchar(20))
END