SQL Server 403 Error When Setting a Geography Type for Update - sql

All I need to do is simply get one geography value from a table and store it in another table. There is some logic for which row to take from the origin table so it's not just a straight select.
In any of 50 possible variants of this, I get this error when hitting the update to the target table:
Msg 403, Level 16, State 1, Line 1
Invalid operator for data type. Operator equals not equal to, type equals geography.
My SQL looks like this at the moment:
declare
#EquipmentId int
, #CurrentLocationId int
, #CurrentGeoLocation geography
, #LastUpdated datetime
select #EquipmentId =
(
select top 1 EquipmentId
from Equipment
order by EquipmentId
)
select #CurrentLocationId = (select top 1 EquipmentLocationId from EquipmentLocation where EquipmentId = #EquipmentId order by LastUpdated desc)
select #LastUpdated = (select top 1 LastUpdated from EquipmentLocation where EquipmentId = #EquipmentId order by LastUpdated desc)
UPDATE
dbo.Equipment
SET
CurrentLocationDateTime = #LastUpdated
, CurrentGeoLocation = (select GeoLocation from EquipmentLocation where EquipmentLocationId = #CurrentLocationId)
, ModifiedBy = 'system'
, ModifiedByUserId = -1
, ModifiedDate = getdate()
WHERE
EquipmentId = #EquipmentId
I have had CurrentGeoLocation set in a variable of the same type, selected into by the same statement you see in the update.
I have had an #CurrentGeoLocation variable populated by a geography::STGeomFromText as well as geography::Point() function call.
I've used Lat and Long variables to call Point and FromText functions.
All the same result, the above 403 error. I could understand it somewhat when I was concatenating various permutations of the GeomFromText function that needs well known text format for the point parameter, but field value to field value is killing me, as is the fact that I get this error no matter how I try to give the origin point data to the target table.
Thoughts?
Update:
I've been experimenting a little and found that the following works just fine:
declare #GL geography
select #GL = (select GeoLocation from EquipmentLocation where EquipmentLocationId = 25482766)
print convert(varchar, #GL.Lat)
print convert(varchar, #GL.Long)
update Equipment set CurrentGeoLocation = geography::Point(#GL.Lat, #GL.Long, 4326)-- #NewGL where EquipmentId = 10518
But then when I apply this plan to the original script, I'm back to the same error.
The data in the test is working off the exact same records as in the original script. The original script is working off a collection of EquipmentIds, on the first one, I encounter this problem. The short test script uses the same EquipmentLocationId and EquipemntId that are the selected values used to update the first Equipment record in my collection.

Solved!
The error had nothing to do with the geography type as SQL reported. By pulling items in and out of the update statement in an effort to isolate why I still get the error even if I save everything but CurrentGeoLocation and then another update for the geography, I found that CurrentLocationDateTime (datetime, null) was the culprit. Deleted the column, added it back. Problem solved. Original script works as expected.
Don't know what happened to that datetime column that caused it to throw errors against a geometry type, but it's fixed.

Related

Spatial Query Postgis

I have a polygon city and polygon data that I import into PostgreSQL, PostGIS. These intersect with cities. The first thing I need to do is to print the id from the city table to the other table, but while doing this, it needs to get the id of the city where the polygon is located. I tried a few functions to do this but got an error. Can you help me design the SQL command line?
update maden_polygon set objectid = maden_polygon.ilce_id
from (SELECT maden_polygon.ilce_id as id ,ankara_ilce.objectid as ilce_id
FROM maden_polygon , ankara_ilce
WHERE st_intersects(maden_polygon.geom, ankara_ilce.geom)) as maden_polygon
where maden_polygon.ilce_id = anakara_ilce.object_id
(ERROR: table name "maden_polygon" specified more than once )
What I want to do is to print the objectid column in the ankara_ilce table to the mine_polygon ilce_id table.
While doing this,
Write the object_id of which mine is within the boundaries of which county.
SELECT
maden_polygon.ilce_id as id ,
ankara_ilce.objectid as ad ,
ankara_ilce.adi as adi
from maden_polygon , ankara_ilce
where St_intersects(ankara_ilce.geom , maden_polygon.geom ) as sorgu
where maden_polygon.id = sorgu.id ;
ERROR: syntax error at or near "as"
LINE 6: ...ntersects(ankara_ilce.geom , maden_polygon.geom ) as sorgu
I think the query is a simple as this:
UPDATE maden_polygon set objectid = ilce_id
FROM ankara_ilce
WHERE st_intersects(maden_polygon.geom, ankara_ilce.geom)
BUT - note that the st_intersects can return multiple records per maden_polygon if your polygons overlap, and that might give you inconsistent results. You could try using st_contains instead (being aware that some records might not update that way). OR, you could match on the centroid of the one polygon e.g.
UPDATE maden_polygon set objectid = ilce_id
FROM ankara_ilce
WHERE st_within(st_centroid(maden_polygon.geom), ankara_ilce.geom)
Good luck!

Update a Table using a Join

I wish to update a table using, but need to use another table to get the correct field. The new information is not taken from another field from another table.
The following SQL statement returns the correct information:
SELECT PURCHASEHEADER.ORDERNOTES
FROM PURCHASEHEADER, ASSEMBLYLINESOURCE
WHERE ASSEMBLYLINESOURCE.HEADERSYSUNIQUEID = 72637001
AND PURCHASEHEADER.ORDERNUMBER = ASSEMBLYLINESOURCE.PURCHASEORDERNUMBER
I have tried the following:
UPDATE PURCHASEHEADER SET PURCHASEHEADER.ORDERNOTES = 'Updated'
WHERE EXISTS (
SELECT 1 FROM ASSEMBLYLINESOURCE
WHERE PURCHASEHEADER.ORDERNUMBER = ASSEMBLYLINESOURCE.PURCHASEORDERNUMBER
) AND ASSEMBLYLINESOURCE.HEADERSYSUNIQUEID = 72637001
An error is returned saying: " ...Column Unknown ASSEMBLYLINESOURCE.HEADERSYSUNIQUEID..." but it does exist as it works in the first query.
I have seen similar posts from Mark Rotteveel dated July 2017, but still can't get it to work.
There is an issue with your closing bracket. Try this, it worked for me.
UPDATE PURCHASEHEADER set PURCHASEHEADER.ORDERNOTES = 'Updated'
WHERE EXISTS (SELECT 1 FROM ASSEMBLYLINESOURCE WHERE
PURCHASEHEADER.ORDERNUMBER = ASSEMBLYLINESOURCE.PURCHASEORDERNUMBER AND
ASSEMBLYLINESOURCE.HEADERSYSUNIQUEID = 72637001)

Using parameters in a SSRS Query

Using SQL Server Report Builder with Visual Studio 2012, I'm trying to do a simple query with a #myDate variable in it something like (there might be error in it but I just wrote it up real quick, real query does not have error :D )
Select * from myTable x
inner join OtherTable y on x.Id = y.Id
where x.date = #myDate or y.date = #myDate
So when I use this, I need to create the parameter for it set the name and the value of the parameter, so it would be #myDate and his value would be equal to
=Parameters!myDate.Value.
I want it to be visible so I can change it at any time to query different date which will sort different data from my table.
So I could set a default value but that's not the problem.
The problem I am encountering is when I run the report, it ask me the date I want to set as parameter. I enter a date and then it crashes.
Here's what the error says :
SQL0206 : The column or the global variable #MYDATE is unfindable. Cause...:#MYDATE was not found as a column of the table *N in *N and was not found as a global variable...etc
So after this error I tried to add
DECLARE #myDate as DATE
But that didn't work either..
So do any of you ever did something like this? Should I try something different?
Thanks for taking the time to help a newbie!
---------------Edit---------------
Code for type mismatch
Select * from myTable x
inner join OtherTable y on x.Id = y.Id
where Date(x.date) = ? or Date(y.date) = ?
So when you create a query like this in a SSRS dataset, it will prompt you to identify the parameters. So I had created 1 parameter of type Date/Time (only type of date available in SSRS) and in the query properties I set both ? to value : [#DateParameter]
So the problem now is the data overflow when comparing the SSRS Date/Time type to database Date type
I've found one way to it. You have to use an expression for the query.
so
="Select * from myTable x
inner join OtherTable y on x.Id = y.Id
where Date(x.date) = &" Parameters!MyDate.Value " &
or Date(y.date) = & " Parameters!MyDate.Value " &"
That's my query. Now I had to give a value to my Parameter, so I created another dataset which had this query in it :
SELECT CURRENT TIMESTAMP
FROM sysibm.sysdummy1
And then with this I had a time, I only needed to format it to my need so I added a column with an expression like this :
=Cdate(Left(Cdate(DateSerial(cdate(Left(Fields!Date_Filter.Value,10)).Year,
cdate(Left(Fields!Date_Filter.Value,10)).Month,
cdate(Left(Fields!Date_Filter.Value, 10)).Day)), 10))
And then I set my parameter's default value to this dataset's column. And then it worked just fine!
Try to declare it as a global variable as ##myDate

SQL WHILE statement error "The column prefix does not match with a table name or alias name used in the query"

I am trying to run the below SQL statement and am getting the below message
The column prefix 'timInvtTran' does not match with a table name or alias name used in the query.
Basically what I'm trying to do is to get the resulting Quantity on Hand (QOH) after each inventory transaction.
An assumption to this is that when summing TranQty you will get the resulting QOH.
I am trying to loop the data and add a running total of TranQty, which would by definition be the QOH. I named my QOH variable as #currQOH .
I know the issue is coming from my SET statement but I can’t figure out why it’s happening.
As a side note, am I on the correct path to getting a running total of TranQty? I don’t want to write to the DB and so I don’t want to create new tables for my running total. I researched high and low and couldn’t find anything.
Any bit of help would be extremely appreciated.
DECLARE #currQOH INT
SET #currQOH=0
WHILE( Select ItemKey from timInvtTran) = 41511
BEGIN
SET #currQOH = #currQOH + timInvtTran.TranQty
BREAK
END
select #currQOH, ItemKey, TranID
from timInvtTran
where timInvtTran.ItemKey = 41511 and substring(tranid,12,2) <>'SH'
order by timinvttran.createdate desc
BTW Happy PI day!
Try this instead
DECLARE #currQOH INT
SET #currQOH= ( select sum(TranQty) from timInvtTran where ItemKey = 41511 )
select #currQOH, ItemKey, TranID
from timInvtTran
where timInvtTran.ItemKey = 41511 and substring(tranid,12,2) <>'SH'
order by timInvttran.createdate desc
Note the case change in the last line: timinvttran -> timInvttran

Getting table(records) to update properply using the MERGE Statement

Good morning everyone!
Below is a piece of code I stitched together: I used a CTE to grab the records(data) from a link table and than convert strings to dates, than use the merge statement to get the data into a local table:
I am having a problem with the column(field) LAST_RACE_DATE this field is set to NULL and is not required but it does not update with my current set up. What I am trying to accomplished is for this field to populate when data is entered but also update, meaning it should also update with NULL.
So if the field has a specific date, and a new date is entered in the remote database, this field should update as well, even if the data is deleted in the back end, it should also remove the local table data for this field.
WITH CTE AS(
SELECT MEMBER_ID
,[MEMBER_DATE] = MAX(CONVERT(DATE, MEMBER_DATE))
,RACE_DATE = MAX(CONVERT(DATE, RACE_DATE))
,LAST_RACE_DATE = MAX(CONVERT(DATE, LAST_RACE_DATE))
FROM [EXAMPLE].[dbo].[LINKED_MEMBER_DATA]
WHERE (MEMBER_DATE IS NOT NULL) AND (ISDATE(MEMBER_DATE)<> 0) AND (RACE_DATE IS NOT NULL) AND (ISDATE(RACE_DATE)<> 0)
AND (LAST_RACE_DATE IS NULL) OR (ISDATE(LAST_RACE_DATE)<> 0)
GROUP BY MEMBER_ID)
MERGE dbo.LINKED_MEMBER_DATA AS Target
USING (SELECT
MEMBER_ID, MEMBER_DATE, RACE_DATE, LAST_RACE_DATE
FROM CTE
GROUP BY MEMBER_ID, RACE_DATE, LAST_RACE_DATE)AS SOURCE ON (Target.MEMBER_ID = SOURCE.MEMBER_ID)
WHEN MATCHED AND
(Target.MEMBER_DATE) <> (SOURCE.MEMBER_DATE)
OR (Target.RACE_DATE) <> (SOURCE.RACE_DATE)
OR ISNULL(TARGET.LAST_RACE_DATE , Target.LAST_RACE_DATE) <> ISNULL(SOURCE.LAST_RACE_DATE, SOURCE.LAST_RACE_DATE)
THEN UPDATE SET
Target.MEMBER_DATE = SOURCE.MEMBER_DATE
,Target.RACE_DATE = SOURCE.RACE_DATE
,Target.LAST_RACE_DATE = SOURCE.LAST_RACE_DATE
WHEN NOT MATCHED BY TARGET THEN
INSERT(
MEMBER_ID, MEMBER_DATE, RACE_DATE, LAST_RACE_DATE)
VALUES (Source.MEMBER_ID, Source.MEMBER_DATE, Source.RACE_DATE, Source.LAST_RACE_DATE);
I also tried this:
ISNULL(Target.LAST_RACE_DATE,'N/A') <> ISNULL(SOURCE.LAST_RACE_DATE,'N/A')
But it generates the below error for dates conversion:
Conversion failed when converting date and/or time from character string.
Thanks a Million!!
Your current statement is failing because the ISNULLs that you have don't do anything (if one of the values is NULL the expression will evaluate to NULL), and NULL values don't compare. Your second attempt doesn't work because ISNULL requires the data types of the two values to be the same, so you could try eg ISNULL(Target.LAST_RACE_DATE, '1970-01-01') <> ISNULL(Source.LAST_RACE_DATE, '1970-01-01').
Another option would be to simply enumerate the different cases (eg, (((Source.LAST_RACE_DATE IS NULL AND Target.LAST_RACE_DATE IS NOT NULL) OR (Source.LAST_RACE_DATE IS NOT NULL AND Target.LAST_RACE_DATE IS NULL) OR (Source.LAST_RACE_DATE <> Target.LAST_RACE_DATE))). Enumerating the different situations makes the code a bit more verbose, but it can result in better performance (whether it is measurably better really depends on how much data you are processing).