MySQL Gurus,
I'm converting some reports from a MSSQL database for usage on a MySQL Database, and don't seem to understand how the DECLARE works in MySQL. Below is the SQL code for the report, as works in MSSQL. I read that DECLARE can only be use in a nested function, I belive, but that just does not sound right to me.
Current Report SQL: (I parse & replace the values of Current & Pending from my app code)
DECLARE #Current int;
DECLARE #Pending int;
SET #Current = [1];
SET #Pending = [3];
Select Ticket.TIcketID,
ISNULL((Select LocationName from Location where LocationID = Ticket.SiteCurrentLocation), 'Invalid Location') as [Current Location],
ISNULL((Select LocationName from Location where LocationID = Ticket.SitePendingLocation), 'Invalid Location') as [Pending Location]
from Ticket
where
(SitePendingLocation > 0 AND SitePendingLocation <> SiteCurrentLocation) AND
(SiteCurrentLocation = #Current OR #Current = 0) AND
(SitePendingLocation = #Pending OR #Current = 0)
Any insight?
Thanks - Andrew
EDIT
Working, converted script - that it may help others:
SET #Current = '1';
SET #Pending = '1';
Select Ticket.TIcketID,
IFNULL((Select LocationName from Location where LocationID = Ticket.SiteCurrentLocation), 'Invalid Location') as `Current Location`,
IFNULL((Select LocationName from Location where LocationID = Ticket.SitePendingLocation), 'Invalid Location') as `Pending Location`
from Ticket
where
(SitePendingLocation > 0 AND SitePendingLocation <> SiteCurrentLocation) AND
(SiteCurrentLocation = #Current OR #Current = 0) AND
(SitePendingLocation = #Pending OR #Current = 0)
You can either use SET by itself (no DECLARE) or replace # with _ or similar (or even no prefix).
I generally prefix mine with _
See What's wrong with this MySQL statement: DECLARE #ID INT for a similar question
As regards your other comment, it's IFNULL in MySql - See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull
It's always the little things... :-)
Related
I want to update a databased based upon results from a case, however my "If" statement doesn't seem to pull information from the right table.
declare #dt datetime
set #dt = GETDATE()
select
Ugenummer = datepart(wk, #dt) - datepart(wk,dateadd(m, DATEDIFF(M, 0, #dt), 0)) + 1,
case when (datepart(wk, #dt) - datepart(wk,dateadd(m, DATEDIFF(M, 0, #dt), 0)) + 1) % 2 = 1
then 'ulige' else 'lige' end Ugelighed;
The above code gets the weeknumber (ugenummer) and determines whether it's odd or even (Ulige/lige)
IF Ugelighed = ulige and datepart(dw,#dt) = 1
THEN
UPDATE laeger
SET Antal=1
WHERE Navn=Lægenavn
I would like to use the information from the first code to update a database in a SQL 2008 server
You aren't using Ugenummer so I edited it out. Also created a variable for Ugelighed, you forgot to create one:
declare #dt datetime
set #dt = GETDATE()
declare #Ugelighed VARCHAR(5);
select
#Ugelighed=case when (datepart(wk, #dt) - datepart(wk,dateadd(m, DATEDIFF(M, 0, #dt), 0)) + 1) % 2 = 1
then 'ulige' else 'lige' end;
In the following statements I used variable #Ugelighed to compare to ulige however it is a VARCHAR so you need to enclose it in single quotes (''). Same for Lægenavn, it is a VARCHAR so enclose it in single quotes:
IF #Ugelighed = 'ulige' and datepart(dw,#dt) = 1
UPDATE laeger
SET Antal=1
WHERE Navn='Lægenavn'
Personally I would have created a BIT field for #Ugelighed since even/odd can be captured as a simple boolean rather than text.
I am using function to update to one column , like
DetailedStatus = dbo.fn_GetProcessStageWiseStatus(PR.ProcessID, PR.ProcessRunID, getdate())
Here 500,000 records are continuously UPDATED in this line. Its like like a loop
So using this function for few records its executing fast but when its 500,000 records executing it becomes very slow...
What can I do to make this execute faster using many records?
Any measures to be taken or any split to be used?
Function:
CREATE FUNCTION [dbo].[fn_GetProcessStageWiseStatus]
(
#ProcessID INT
,#ProcessRunID INT
,#SearchDate SMALLDATETIME
)
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE
#iLoopCount SMALLINT
,#iRowCount SMALLINT
,#StepProgress VARCHAR(100)
,#StepCount SMALLINT
IF EXISTS(
SELECT TOP 1 1
FROM dbo.Step S WITH(NOLOCK)
JOIN dbo.vw_FileGroup FG
ON S.FileConfigGroupID = FG.FileConfigGroupID
WHERE S.ProcessID = #ProcessID
AND S.Active = 1
AND FG.FileConfigGroupActive = 1
AND FG.Direction = 'Inbound'
)
BEGIN
SET #StepProgress = 'Not Received'
END
ELSE
BEGIN
SET #StepProgress = 'Not Started'
END
DECLARE #StepRunDetailsTable TABLE
(
KeyNo INT IDENTITY(1,1)
,StepID INT
,StepStartTime SMALLDATETIME
,StepEndTime SMALLDATETIME
,SourceEnv VARCHAR(100)
,DestEnv VARCHAR(100)
)
INSERT INTO #StepRunDetailsTable
SELECT
S.StepID
,MAX(isnull(SR.StepStartTime, '06/06/2079'))
,MAX(isnull(SR.StepEndTime, '06/06/2079'))
,isnull(SENV.EnvironmentName, '')
,isnull(DENV.EnvironmentName, '')
FROM dbo.ProcessRun PR WITH(NOLOCK)
JOIN dbo.StepRun SR WITH(NOLOCK)
ON SR.ProcessRunID = PR.ProcessRunID
JOIN dbo.vw_StepHierarchy SH
ON SR.StepID = SH.StepID
AND SH.Active = 1
JOIN dbo.Step S WITH(NOLOCK)
ON SH.StepID = S.StepID
JOIN dbo.WorkFlow WF WITH(NOLOCK)
ON S.WorkFlowID = WF.WorkFlowID
AND WF.Active = 1
JOIN dbo.Environment SENV WITH(NOLOCK)
ON SENV.EnvironmentID = WF.SourceEnvironmentID
AND SENV.Active = 1
JOIN dbo.Environment DENV WITH(NOLOCK)
ON DENV.EnvironmentID = WF.DestinationEnvironmentID
AND DENV.Active = 1
WHERE PR.ProcessRunID = #ProcessRunID
GROUP BY S.StepID, SENV.EnvironmentName, DENV.EnvironmentName, SH.StepOrder
ORDER BY SH.StepOrder ASC
SELECT #StepCount = COUNT(*)
FROM dbo.ProcessRun PR WITH(NOLOCK)
JOIN dbo.Step S WITH(NOLOCK)
ON PR.ProcessID = S.ProcessID
AND PR.ProcessRunID = #ProcessRunID
AND S.Active = 1
SELECT #iRowCount = COUNT(DISTINCT StepID) FROM #StepRunDetailsTable
SET #iLoopCount = 0
WHILE (#iRowCount > #iLoopCount)
BEGIN
SET #iLoopCount = #iLoopCount + 1
SELECT
#StepProgress =
CASE
--WHEN #SearchDate BETWEEN StepStartTime AND StepEndTime
WHEN #SearchDate >= StepStartTime AND #SearchDate <= StepEndTime
THEN DestEnv + ' Load in Progress'
WHEN #SearchDate > StepEndTime AND #iLoopCount < #StepCount
THEN 'Waiting on next step - Loaded to ' + DestEnv
WHEN #SearchDate > StepEndTime AND #iLoopCount = #StepCount
THEN 'Completed'
WHEN #SearchDate < StepStartTime AND #iLoopCount = 1
THEN 'Load Not Started'
ELSE #StepProgress
END
FROM #StepRunDetailsTable
WHERE KeyNo = #iLoopCount
END
RETURN #StepProgress
END
Thanks in advance.
Seems like you have a change in execution plan when you try to update 500k rows.
You can try and set forceseek hint on the from clause to force using seeks instead of scans.
Also, WHILE (#iRowCount > #iLoopCount) should be replaced with if exists, because you basically check for certain conditions on the results table and you need to return as early as possible.
I see that you use nolock hint everywhere to allow dirty reads, you can set isolation level read uncommitted in the calling stored procedure and remove all of those; or consider to change the database to set read_committed_snapshot on to avoid locks.
By the way, scalar function calls in SQL Server are very expensive, so if you have some massive updates/selects happening in a loop where you call a function you have to avoid using functions as much as possible.
I have searched but been unable to find anything that does what I need.
I would like to create a stored function that will gather data from a secondary field and return a comma separated list of items as the return string. I can't seem to find any way to take a variable I create in the function and iterate through a record set and append each result to the variable so I can return it .. see below:
BEGIN
DECLARE searchCat INT;
DECLARE searchProd INT;
DECLARE metas CHAR;
SET searchCat = cat;
SET searchProd = prod;
SELECT * FROM offer_metas WHERE category = searchCat AND offer_id = searchProd
gatherMeta: LOOP
metas = metas + "," + meta_option;
ITERATE gatherMeta;
END LOOP gatherMeta;
RETURN metas;
END
The function won't save because my syntax on the "metas = metas + meta_option;".
What I am looking for is the command to append the current field falue of "meta_option" to the current variable "metas" so I can return a full list at the end.
Any idea?
UPDATE - SOLUTION
BEGIN
DECLARE metas VARCHAR (300);
SELECT GROUP_CONCAT(CONCAT(mn.title,'=',offer_metas.meta_option) ORDER BY mo.cat_seq ASC) INTO metas
FROM offer_metas
LEFT JOIN meta_options as mo ON mo.id = offer_metas.meta_option
LEFT JOIN meta_names AS mn ON mn.category = mo.category AND mn.seq = mo.cat_seq
WHERE offer_metas.category = searchCat
AND offer_metas.offer_id = searchProd
ORDER BY cat_seq ASC;
RETURN metas;
END
And then I just updated my SQL query to be as follows (1 is the offer category I have in my PHPand populate into the query):
SELECT offers.*, s.short_name AS sponsorName, s.logo AS sponsorLogo, getMetas(1,offers.id) AS metas
FROM offers
LEFT JOIN sponsors AS s ON s.id=offers.carrier
GROUP BY offers.id
ORDER BY end_date ASC
Why not just
SELECT GROUP_CONCAT(meta_option SEPARATOR ',')
FROM offer_metas
WHERE category = searchCat AND offer_id = searchProd;
Option 1) use Group_Concat
Option 2) use || instead of +
Option 3) use Concat()
Presently troubleshooting a problem where running this SQL query:
UPDATE tblBenchmarkData
SET OriginalValue = DataValue, OriginalUnitID = DataUnitID,
DataValue = CAST(DataValue AS float) * 1.335
WHERE
FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND ZEGCodeID IN
(SELECT ZEGCodeID FROM tblZEGCode
WHERE(ZEGCode = 'C004') OR
(LEFT(ZEGParentCode, 4) = 'C004'))
Results in the following error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
The really odd thing is, if I change the UPDATE to SELECT to inspect the values that are retrieved are numerical values:
SELECT DataValue
FROM tblBenchmarkData
WHERE FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND ZEGCodeID IN
(SELECT ZEGCodeID
FROM tblZEGCode WHERE(ZEGCode = 'C004') OR
(LEFT(ZEGParentCode, 4) = 'C004'))
Here are the results:
DataValue
2285260
1205310
Would like to use TRY_PARSE or something like that; however, we are running on SQL Server 2008 rather than SQL Server 2012. Does anyone have any suggestions? TIA.
It would be helpful to see the schema definition of tblBenchmarkData, but you could try using ISNUMERIC in your query. Something like:
SET DataValue = CASE WHEN ISNUMERIC(DataValue)=1 THEN CAST(DataValue AS float) * 1.335
ELSE 0 END
Order of execution not always matches one's expectations.
If you set a where clause, it generally does not mean the calculations in the select list will only be applied to the rows that match that where. SQL Server may easily decide to do a bulk calculation and then filter out unwanted rows.
That said, you can easily write try_parse yourself:
create function dbo.try_parse(#v nvarchar(30))
returns float
with schemabinding, returns null on null input
as
begin
if isnumeric(#v) = 1
return cast(#v as float);
return null;
end;
So starting with your update query that's giving an error (please forgive me for rewriting it for my own clarity):
UPDATE B
SET
OriginalValue = DataValue,
OriginalUnitID = DataUnitID,
DataValue = CAST(DataValue AS float) * 1.335
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
I think you'll find that a SELECT statement with exactly the same expressions will give the same error:
SELECT
OriginalValue,
DataValue NewOriginalValue,
OriginalUnitID,
DataUnitID OriginalUnitID,
DataValue,
CAST(DataValue AS float) * 1.335 NewDataValue
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
This should show you the rows that can't convert:
SELECT
B.*
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
AND IsNumeric(DataValue) = 0
-- AND IsNumeric(DataValue + 'E0') = 0 -- try this if the prior doesn't work
The trick in the last commented line is to tack on things to the string to force only valid numbers to be numeric. For example, if you wanted only integers, IsNumeric(DataValue + '.0E0') = 0 would show you those that aren't.
I have a MySQL stored procedure and in it, the following WHILE statement.
I have confirmed that #RowCnt is 1, and #MaxRows is 6090, however after further debugging, I realized that the WHILE statement is going through a single iteration and not continuing; so I'm hoping to have some light shed on what could possibly be causing this.
Full disclosure: I ported this from SQL Server to a MySQL stored procedure, something I have never taken on before. (meaning SQL Server, porting OR stored procedures..)
WHILE #RowCnt <= #MaxRows DO
SELECT #currentReadSeq:=ReadSeq, #currentReadStrength:=ReadStrength, #currentReadDateTime:=ReadDateTime, #currentReaderID:=ReaderID FROM tblTempRead WHERE rownum = #RowCnt;
IF ( ((#lastReadSeq + 10) > #currentReadSeq) AND (#lastReaderId = #currentReaderId) ) THEN
SET #lastReadSeq = #currentReadSeq, #lastReadStrength = #currentReadStrength, #lastReadDateTime = #currentReadDateTime, #lastReaderID = #currentReaderID;
ELSE
INSERT INTO tblreaddataresults (SiteID, ReadDateTimeStart, ReadDateTimeEnd, ReadSeqStart, ReadSeqEnd, ReaderID, DirectSeconds) VALUES ('1002', #saveReadDateTime, #lastReadDateTime, #saveReadSeq, #lastReadSeq, #lastReaderID, timestampdiff(SECOND,#saveReadDateTime,#lastReadDateTime));
SET #saveReadSeq = #currentReadSeq, #saveReadStrength = #currentReadStrength, #saveReadDateTime = #currentReadDateTime, #saveReaderID = #currentReaderID;
SET #lastReadSeq = #saveReadSeq, #lastReadStrength = #saveReadStrength, #lastReadDateTime = #saveReadDateTime, #lastReaderID = #saveReaderID;
END IF;
SET #RowCnt = #RowCnt+1;
END WHILE;
Try This Construct
WHILE (#RowCnt <= #MaxRows)
BEGIN
SELECT #currentReadSeq:=ReadSeq, #currentReadStrength:=ReadStrength, #currentReadDateTime:=ReadDateTime, #currentReaderID:=ReaderID FROM tblTempRead WHERE rownum = #RowCnt;
IF (((#lastReadSeq + 10) > #currentReadSeq) AND (#lastReaderId = #currentReaderId))
BEGIN
SET #lastReadSeq = #currentReadSeq, #lastReadStrength = #currentReadStrength, #lastReadDateTime = #currentReadDateTime, #lastReaderID = #currentReaderID;
END
ELSE
BEGIN
INSERT INTO tblreaddataresults (SiteID, ReadDateTimeStart, ReadDateTimeEnd,ReadSeqStart, ReadSeqEnd, ReaderID, DirectSeconds) VALUES ('1002',#saveReadDateTime, #lastReadDateTime, #saveReadSeq, #lastReadSeq, #lastReaderID,timestampdiff(SECOND,#saveReadDateTime,#lastReadDateTime));
SET #saveReadSeq = #currentReadSeq, #saveReadStrength = #currentReadStrength, #saveReadDateTime = #currentReadDateTime, #saveReaderID = #currentReaderID;
SET #lastReadSeq = #saveReadSeq, #lastReadStrength = #saveReadStrength,#lastReadDateTime = #saveReadDateTime, #lastReaderID = #saveReaderID;
END
SET #RowCnt = #RowCnt+1;
END