SQL Field Update Syntax Issues with complex selection logic - mysql

The query below works fine and is what I need.
I want to add a new keyword onto "Keywords" e.g.
UPDATE bugs SET bug.keywords = CONCAT(bug.keywords, ', Report:DevProcess')
However no matter where I place this in the logic below, I get a syntax error.
The web examples I have seen and in Stackoverflow are for simple
Update ... WHERE .... examples.
SET #StartDate = '2016-03-01';
SET #EndDate = '2016-03-31';
SELECT
bugs_activity.bug_id,
bug.status_whiteboard AS Whiteboard,
bug.keywords AS Keywords,
bug.bug_status,
bug.resolution,
SUM(CASE WHEN fd.name = 'bug_status' AND (bugs_activity.added = 'VERIFIED' OR bugs_activity.added = 'CLOSED') THEN 1 ELSE 0 END) AS ClosedCount,
MIN(CASE WHEN fd.name = 'bug_status' AND bugs_activity.added = 'VERIFIED' THEN bug_when ELSE NULL END) AS verifiedDate,
MIN(CASE WHEN fd.name = 'bug_status' AND bugs_activity.added = 'CLOSED' THEN bug_when ELSE NULL END) AS closedDate
FROM bugs_activity
INNER JOIN bugs bug
ON bugs_activity.bug_id = bug.bug_id
INNER JOIN fielddefs fd
ON bugs_activity.fieldid = fd.id
WHERE
(bugs_activity.bug_when BETWEEN '2015-09-01' AND #EndDate)
AND (Keywords LIKE '%Region:Europe%')
AND NOT (Keywords LIKE '%Report:DevProcess%')
GROUP BY bug_id
HAVING
ClosedCount > 0
AND (
(verifiedDate IS NOT NULL AND verifiedDate >= #StartDate)
OR (verifiedDate IS NULL AND (closedDate IS NOT NULL AND closedDate >= #StartDate))
)
Additional info from questions:
Linqpad SQL talking to MySQL DB
From linqpad - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE bugs SET bug.keywords = CONCAT(bug.keywords, ', Report:DevProcess')' at line 20
I removed GroupBy line, same error.
CONCAT is what a web search tells me How to prepend a string to a column value in MySQL?
In the selected "bugs" I want to "UPDATE bugs SET bug.keywords = CONCAT(bug.keywords, ', Report:DevProcess') "
Bugzilla has historically for a long time used multiple keywords. It is what it is whether good or bad.
== 31/05/2016 update ==
I simplified the query and got past the syntax error, however no update. I confirmed account had DB write access by using the read account which produced an access denied error.
-- this shows the one record
SELECT bug_id
FROM bugs
WHERE (bugs.bug_status = 'VERIFIED') AND (bugs.status_whiteboard LIKE '%Leiden%') and (bugs.keywords LIKE '%Region:Europe%') AND NOT (bugs.keywords LIKE '%Report:DevProcess%')
-- this runs without an error but shows no records updated
UPDATE bugs SET bugs.keywords = CONCAT(bugs.keywords, ', Report:DevProcess')
WHERE (bugs.bug_status = 'VERIFIED') AND (bugs.status_whiteboard LIKE '%Leiden%') and (bugs.keywords LIKE '%Region:Europe%') AND NOT (bugs.keywords LIKE '%Report:DevProcess%')

The simpler syntax does "work", i.e. no syntax error however the write did not work initially. This turned out to be because the keyword schema required the keyword to be pre-defined. Adding the keyword in resulting in the record being updated.
-- this runs without an error but shows no records updated
UPDATE bugs SET bugs.keywords = CONCAT(bugs.keywords, ', Report:DevProcess')
WHERE (bugs.bug_status = 'VERIFIED') AND (bugs.status_whiteboard LIKE '%Leiden%') and (bugs.keywords LIKE '%Region:Europe%') AND NOT (bugs.keywords LIKE '%Report:DevProcess%')

Related

Porting SQLite View to MySQL

I have to "port" an SQLite database to MySQL. The database is set up from a C# application with the Connector/NET lib.
Porting the methods for creating the tables of the DB was straight forward, but I got stuck at a view.
The SQLite code for the view works just fine and looks like the following:
CREATE VIEW IF NOT EXISTS EXO_ResultsSummaries AS
SELECT ParticipantBIB,
t.HeatIndex,
(CASE WHEN t.QualiGroup IS NULL THEN t.Finals ELSE t.QualiGroup END) AS HeatLevel,
PointsObstacle0 + PointsObstacle1 AS TotalScore, TimeObstacle0 + TimeObstacle1 AS TotalTime
FROM (EXO_Results INNER JOIN Heats ON EXO_Results.HeatIndex = Heats.HeatIndex) t
WHERE t.Completed = 1;
Since the "IF NOT EXISTS" statement does not work with MySQL, I changed the code to the following:
CREATE OR REPLACE VIEW EXO_ResultsSummaries AS
SELECT ParticipantBIB,
t.HeatIndex,
(CASE WHEN t.QualiGroup IS NULL THEN t.Finals ELSE t.QualiGroup END) AS HeatLevel,
PointsObstacle0 + PointsObstacle1 AS TotalScore, TimeObstacle0 + TimeObstacle1 AS TotalTime
FROM (EXO_Results INNER JOIN Heats ON EXO_Results.HeatIndex = Heats.HeatIndex) AS t
WHERE t.Completed = 1;
However, if I try to create the view from my application (or from the workbench), I get this error:
Error Code: 1064. You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS t WHERE t.Completed = 1' at line 6
Thanks to Shadow for his comments. Changed my code accordingly and this worked just fine:
CREATE OR REPLACE VIEW EXO_ResultsSummaries AS SELECT ParticipantBIB,
Heats.HeatIndex,
(CASE WHEN Heats.QualiGroup IS NULL THEN Heats.Finals ELSE Heats.QualiGroup END) AS HeatLevel,
PointsObstacle0 + PointsObstacle1 AS TotalScore, TimeObstacle0 + TimeObstacle1 AS TotalTime
FROM EXO_Results INNER JOIN Heats ON EXO_Results.HeatIndex = Heats.HeatIndex
WHERE Heats.Completed = 1;

I want to add two new fields to a view which is not related to a table with a case statement

1) I am creating a Calendar View and I would like to add a column which checks if the date in that row is a working day if so then populate with 1, else 0.
I have a table with all UK public holidays and in the calendar table I also have a 'dayoftheweek' field where 1 and 7 is SUN and SAT.
Currently I am trying use a case statement, however I cannot run the script as receive the following error:
SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(CASE IF CT.dayofweek = `1` OR CT.dayofweek = `7` OR CT.dt = PH.`H' at line 12 (edited)
This is my script:
ALTER VIEW Calendar_View AS
select `calendar_table`.`dt` AS `date`,
`calendar_table`.`year` AS `year`,
`calendar_table`.`quarter` AS `quarter`,
`calendar_table`.`month` AS `month`,
`calendar_table`.`day` AS `day`,
`calendar_table`.`dayofweek` AS `dayofweek`,
`calendar_table`.`monthName` AS `monthName`,
`calendar_table`.`dayName` AS `dayName`,
`calendar_viewtable`.`week` AS `week`,
`calendar_table`.`isWeekday` AS `isWeekday`
(CASE
WHEN CT.dayofweek = `1` THEN `0'
WHEN CT.dayofweek = `7` THEN `0`
WHEN CT.dt = PH.`Holiday Date` THEN `0`
ELSE `1`
END CASE ) AS IsWorkingDay
from `calendar_table` CT, `Public_Holidays` PH
2) I would also like to add another field which checks if the date in the calendar is the current date and so the populate new field with Yes, else No (I tried using a case statement this didnt work).
This is your code:
(CASE WHEN CT.dayofweek = `1` THEN `0'
WHEN CT.dayofweek = `7` THEN `0`
WHEN CT.dt = PH.`Holiday Date` THEN `0`
ELSE `1`
END CASE ) AS IsWorkingDay
This is what you want:
(CASE WHEN CT.dayofweek = 1 THEN 0
WHEN CT.dayofweek = 7 THEN 0
WHEN CT.dt = PH.`Holiday Date` THEN 0
ELSE 1
END) AS IsWorkingDay
There are two important differences:
END CASE is not valid syntax.
When you use backticks, you are saying that the string is an identifier -- typically a column reference. There are no columns called 0 or 1.
Two other issues with your query are the missing comma and the lack of join conditions. Your from clause should look more like:
from calendar_table ct left join
Public_Holidays ph
on ct.dt = ph.dt -- or whatever the right condition is

Select SQL statement from multiple database

My question has 2 parts, and i am unsure if it is my query which is causing the error or data adapter.
Part 1. I have a mySQL query which works fine on SQLyog, the query involves selection from tables existing in different databases. And both databases has been set to have the same accecss rights for the user account used at the connection string.
Below will be my query.
SELECT `portaldb`.`users`.`full_name` AS 'Name of User'
,`Systemrevamp`.`System_countries`.`CountryName` AS 'Quoted For'
,`Systemrevamp`.`uniquequote`.`UniqueQuote` AS 'System Quote ID'
, IF (
LEFT(`Systemrevamp`.`uniquequote`.`username`, 1) = ' '
,'Web Access'
,'Bulk Upload'
) AS 'Type'
,DATE_FORMAT(`Systemrevamp`.`uniquequote`.`insertedon`, '%d-%b-%Y') AS 'Quoted On'
FROM `portaldb`.`users`
INNER JOIN `Systemrevamp`.`uniquequote` ON TRIM(`Systemrevamp`.`uniquequote`.`UserName`) = `portaldb`.`users`.`usrname`
INNER JOIN `Systemrevamp`.`System_countries` ON `Systemrevamp`.`System_countries`.`Code` = `Systemrevamp`.`uniquequote`.`CountryCode`
INNER JOIN `portaldb`.`permission_details` ON `portaldb`.`permission_details`.`user_ID` = `portaldb`.`users`.`user_ID`
WHERE `portaldb`.`permission_details`.`group_ID` = '5'
AND `Systemrevamp`.`uniquequote`.`insertedon` >= (NOW() - INTERVAL 3 MONTH)
ORDER BY `portaldb`.`users`.`full_name` ASC,`Systemrevamp`.`uniquequote`.`insertedon` ASC
Visual studio keeps telling me there is syntax error and to check the version of SQL, but I am able to retrieve at the database.
Part 2. Below is a snippet of my code. My question for this part is, if the above query is used, what source table should I put for the data adapter to fill at 'XXX'?
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
allUserDataset = New DataSet()
myDataAdapter.Fill(allUserDataset, "XXX")
gvAllQuotes.DataSource = allUserDataset
gvAllQuotes.DataBind()
Please let me know if more information is needed. Thank you.

Getting error using EXECUTE('UPDATE..') on a MySQL server from SQL Server

I intend to do:
EXECUTE('UPDATE tableA SET campaignkey = ''20170101'' where storekey = 16
and campaignkey LIKE ''%,%''') at MYLINKEDSERVER
but I get the error that:
You have an error in your SQL syntax; [...] for the right syntax to use near 'where storekey = 16 and campaignkey LIKE '%,%''
Does anyone have any idea what is wrong? To me it seems like I might have one ' too many on my LIKE statement, but I have Always used '' to indicate a non-numeric value. I don't want to fiddle with this to prevent updating far too many values on this server.
campaignkey is non-numeric (I Believe varchar) and storekey is integer.
Edit
I must not use OPENQUERY() because it is not set up correctly, and this is a urgent update.
Edit 2
Seems like it is because of apostrophes 's in the EXECUTE statement.
When I conduct:
select * from openquery(linkedserver,'Select * from tableA where storekey = 16
and campaignkey = ''20170826,151''')
it works, but when using:
EXECUTE('Select * from tableA where storekey = 16
and campaignkey = ''20170826,151''') at linkedserver
I get the error that I need to check the manual by the where clause. From googling it appears however that the correct syntax in fact is:
EXECUTE('UPDATE TableX SET StringVar = ''stringValue'' WHERE intVar = 3
AND stringVar = ''xxxxx''') AT LinkedServer
I don't know why this won't work for me.. I have tried many combinations of '', '" etc.
What about this one?
update openquery(linkedserver,'Select * from tableA where storekey = 16
and campaignkey = ''20170826,151''')
set campaignkey = '20170101'

Comparing dates in iif() in SQL Server

I am trying to use the following query in SQL Server
SELECT [AL].[Subscriptions].Id,
[AL].[Subscriptions].name,
[AL].[Subscriptions].description,
[AL].[Subscriptions].price,
[AL].[Subscriptions].iconFileName,
IIf(a.expiryDate > Now(), 'TRUE', 'FALSE') AS isSubsByUser
FROM [AL].[Subscriptions]
LEFT JOIN (SELECT *
FROM [AL].[UserSubscriptions]
WHERE userId = 13259) AS a
ON Subscriptions.Id = a.itemid;
but always get the error
Error in list of function arguments: '>' not recognized.
Unable to parse query text.
How do I resolve it?
Like Martin Smith said you need to use a case statement. Also it looks like you are only using a couple of fields in the derived table therefor I would suggest not using *. I put a example below.
SELECT [AL].[Subscriptions].Id,
[AL].[Subscriptions].name,
[AL].[Subscriptions].description,
[AL].[Subscriptions].price,
[AL].[Subscriptions].iconFileName,
case when a.expiryDate > GetDate() then 'TRUE' else 'FALSE' end AS isSubsByUser
FROM [AL].[Subscriptions]
LEFT JOIN (SELECT expiryDate, itemid
FROM [AL].[UserSubscriptions]
WHERE userId = 13259) AS a
ON Subscriptions.Id = a.itemid;