Create MySQL procedures - mysql

I am currently trying to create a stored procedure on my MySQL stored on Google Cloud Platform.
The SQL is correct seeing that I can create the procedure locally, but I can't figure out why it won't work from the command line:
mysql> CREATE PROCEDURE helpme
-> (
-> #cid varchar(4)
-> )
-> AS
-> DECLARE #res_cnt INT
-> DECLARE #name CHAR(10)
->
-> SELECT #res_cnt = COUNT(*) FROM dbo.TripGuides WHERE GuideNum = #cid
-> SELECT #name = LastName FROM dbo.Guide WHERE GuideNum = #cid
-> PRINT #name + ' has ' + CAST (#res_cnt AS VARCHAR(10))+' guides.';
ERROR 1064 (42000): 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 '#cid varchar(4)
)
AS
DECLARE #res_cnt INT
DECLARE #name CHAR(10)
SELECT #res_cn' at line 3
mysql>
I've tried a few different things thank I have bumped into. When declaring #cid I tried both
#cid CHAR(4)
#cid VARCHAR(4)
resulting in the same error being thrown.

For MySQL use
CREATE PROCEDURE helpme ( cid VARCHAR(4) )
SELECT CONCAT( ( SELECT LastName
FROM Guide
WHERE GuideNum = cid ),
' has ',
( SELECT COUNT(*)
FROM TripGuides
WHERE GuideNum = cid ),
' guides.'
) AS message;
Just out of curiosity how would I go about declaring res_cnt and name as to the original SQL call i did before?
CREATE PROCEDURE helpme ( cid VARCHAR(4) )
BEGIN
DECLARE res_cnt INT;
DECLARE `name` CHAR(10);
SELECT COUNT(*) INTO res_cnt FROM TripGuides WHERE GuideNum = cid;
SELECT LastName INTO `name` FROM Guide WHERE GuideNum = cid;
SELECT CONCAT( `name`, ' has ', res_cnt, ' guides.' ) AS output_message;
END
And do not forget about DELIMITER re-assign in that case.

Related

Incorrect syntax while parsing JSON with OPENJSON

This is my SP, I am trying to parse this and the error
Incorrect syntax near '$.Role'
was shown.
The JSON is stored in a tables's column. What am I doing wrong?
CREATE PROCEDURE [dbo].[sp_GetKeyPersonRoleMinMax]
#SectionID INT,
#ProposalID INT
AS
SET NOCOUNT ON
Declare #FldKPRoleRequirementsList NVARCHAR(MAX)
Declare #FldName varchar(50)
DEclare #FldIncl varchar(50)
Declare #FldRequired varchar(50)
Declare #FldLabel varchar(max)
Declare #FldList varchar(max)
CREATE Table #RoleMinMaxTemp
(
ID INT IDENTITY(1, 1) ,
Role nvarchar(1000),
MinRoleCount INT,
MaxRoleCount INT
)
Declare Fld_Cursor Cursor For
SELECT FldName, FldIncl, FldRequired, FldLabel,FldList from tblFld where FldParent = 1367 AND FldName like 'FldKPRoleRequirementsList%'
SET NOCOUNT ON
Open Fld_Cursor
WHILE (##Fetch_Status = 0)
BEGIN
if (#FldName = 'FldKPRoleRequirementsList')
BEGIN
SET #FldKPRoleRequirementsList = #FldList
END
FETCH next from Fld_Cursor into #FldName, #FldIncl, #FldRequired, #FldLabel,#FldList
END
Close Fld_Cursor
Deallocate Fld_Cursor
IF(#FldKPRoleRequirementsList IS NOT NULL and Len(#FldKPRoleRequirementsList) >0)
BEGIN
INSERT INTO #RoleMinMaxTemp
SELECT *
FROM OPENJSON(#FldKPRoleRequirementsList,'$.FldRole')
WITH (
Role nvarchar(1000) '$.Role',
MinRoleCount INT '$.MinRoleCount',
MaxRoleCount INT '$.MaxRoleCount'
);
END;
What is the reason for this error? I am using SQL Server 2016.
Try changing you compactibility of SQL SERVER to 130. Your must be below that.
ALTER DATABASE <DatabaseName> SET COMPATIBILITY_LEVEL = 130
Use this script to change it.

MySQL error after attempting to convert Microsoft SQL function

I am trying to convert a function I made in Microsoft SQL into a function for MySQL however I have absolutely no clue how to do that. I tried converting the original code through SQLines and messing with it to no avail.
The working Microsoft code is
ALTER FUNCTION [dbo].[TotalTripsGuideFunc] (#guideid CHAR(4))
RETURNS VARCHAR
BEGIN
DECLARE #trip_counts INT
DECLARE #results VARCHAR
SELECT #trip_counts = COUNT(*) FROM dbo.Reservation,dbo.TripGuides WHERE Reservation.TripID = TripGuides.TripID AND TripGuides.GuideNum = #guideid
SELECT #results = #guideid + ' has ' + CAST (#trip_counts AS VARCHAR(4))+ ' guides '
RETURN #results
END
and the attempted MySql code is
DELIMITER //
CREATE FUNCTION TotalTripsGuideFunc (p_guideid CHAR(4))
RETURNS VARCHAR(1)
BEGIN
DECLARE v_trip_counts INT DEFAULT 0;
DECLARE v_results VARCHAR(1);
SELECT COUNT(*) INTO v_trip_counts FROM Reservation,TripGuides
WHERE Reservation.TripID = TripGuides.TripID AND TripGuides.GuideNum = p_guideid;
SELECT v_results = concat(p_guideid , ' has ', CAST(v_trip_counts AS CHAR), ' guides ');
RETURN v_results;
END;
//
DELIMITER ;
Which returns the error
1415 - Not allowed to return a result set from a function
EDIT
Here is the revised code
DELIMITER //
CREATE FUNCTION TotalTripsGuideFunc (p_guideid CHAR(4))
RETURNS VARCHAR
BEGIN
DECLARE v_trip_counts INT DEFAULT 0;
DECLARE v_results VARCHAR(30);
SELECT COUNT(*) INTO v_trip_counts FROM Reservation,TripGuides
WHERE Reservation.TripID = TripGuides.TripID AND TripGuides.GuideNum = p_guideid;
SET v_results = concat(p_guideid , ' has ', v_trip_counts, ' guides ');
RETURN v_results;
END;
//
DELIMITER ;
Which returns the new error
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'BEGIN DECLARE v_trip_counts INT DEFAULT 0; DECLARE v_results VARCHAR(3' at line 3
Small mistakes:
DECLARE v_results VARCHAR(1); should be a little bigger like DECLARE v_results VARCHAR(30);
RETURNS VARCHAR(1) should be RETURNS VARCHAR
You used the select into right in the first select and wrong in the second. Just need to fix it:
-- from
SELECT v_results = concat(p_guideid , ' has ', CAST(v_trip_counts AS CHAR), ' guides ');
-- to
SELECT concat(p_guideid , ' has ', v_trip_counts, ' guides ') INTO v_results;
-- OR just:
SET v_results = concat(p_guideid , ' has ', v_trip_counts, ' guides ');
-- no need for CAST, MySQL will do implicit conversion
EDIT: here is a working final version:
DELIMITER //
CREATE FUNCTION TotalTripsGuideFunc (p_guideid VARCHAR(30)) RETURNS VARCHAR(30)
BEGIN
DECLARE v_trip_counts INTEGER;
DECLARE v_results VARCHAR(30);
SELECT COUNT(*) INTO v_trip_counts FROM Reservation,TripGuides
WHERE Reservation.TripID = TripGuides.TripID AND TripGuides.GuideNum = p_guideid;
SET v_results = concat(p_guideid , ' has ', v_trip_counts, ' guides ') ;
RETURN v_results;
END
//
DELIMITER ;
I think you should return like this RETURN ( v_results )

Sql syntax error in procedure

I am writing one procedure in order to get data from database .
Here is my procedure .
CREATE DEFINER=`root`#`localhost` PROCEDURE `getCdrListnew`(from_date DATETIME, to_date DATETIME,
p_category VARCHAR(255), p_callType VARCHAR(255), p_businessId VARCHAR(255), p_dnc VARCHAR(255),
p_cli VARCHAR(255), p_dni VARCHAR(255), p_callNumber VARCHAR(255), p_dialType VARCHAR(255), p_contractType VARCHAR(255) )
BEGIN
DECLARE a INT ;
DECLARE setFilter INT DEFAULT FALSE;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET a = 0;
BEGIN
END;
SET #sqlCalls = 'SELECT agentcdr.isdnCauseCode,COUNT(*) as count FROM cdr';
-- SET #sqlCalls= CONCAT(#sqlCalls,' LEFT JOIN agentcdr ON cdr.idCDR=agentcdr.cdr_idCDR ');
IF( (from_date IS NOT NULL AND from_date != '')&& (to_date IS NOT NULL AND to_date != '') ) THEN
SET #sqlCalls= CONCAT(#sqlCalls,' WHERE cdr.createdDt >=\'',from_date,'\' AND cdr.createdDT<=', '\'',to_date,'\'');
SET setFilter = TRUE;
END IF;
SET #sqlCalls= CONCAT(#sqlCalls,' LEFT JOIN agentcdr ON cdr.idCDR=agentcdr.cdr_idCDR GROUP BY agentcdr.isdnCauseCode ');
PREPARE prepsqlstr1 FROM #sqlCalls;
EXECUTE prepsqlstr1;
END
When I am executing the above code I am getting an error as below .
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 'LEFT JOIN agentcdr ON cdr.idCDR=agentcdr.cdr_idCDR GROUP BY agentcdr.isdnCauseCo' at line 1
I know this is the syntax problem but not able to figure out what I am doing wrong here .
Please help me out .
ALso do let me know if there any way to print the query which is executing in procedure for debugging purpose .
Looks like you have a wrong order in the generated statement:
You get a select ... where ... left join .... This is wrong syntax.

When I am trying to drop tables using below script , it seems not working.

I am trying to drop tables from each server. My Server 1 has 3 Databases and Server 2 has 6 and Server 3 has 8.
Below is the SQL Script that I wrote to perform the drop operation from each databases in in particular server. After I perform these operation.
DECLARE
#LoopId int,
#Command varchar(500),
#tblName varchar(100)
DECLARE #List TABLE
(
TableName sysname not null,
LoopId int not null identity(1,1)
)
-- Load with tables you wish to drop
INSERT #List (TableName)
SELECT name FROM [Morgage].sys.objects WHERE type = 'u' and name like '%JKL%'
SELECT name FROM [Scorecard].sys.objects WHERE type = 'u'and name like '%JKL%'
SELECT name FROM [Core].sys.objects WHERE type = 'u' and name like '%JKL%'
SET #LoopId = ##rowcount
-- Go through list and process each item
WHILE #LoopId > 0
BEGIN
SET #tblName = (SELECT TableName from #List where LoopId = #LoopId)
SET #Command = 'Drop table ' + #tblName
execute (#Command)
SET #LoopId = #LoopId - 1
END
Above query result says rows affected but then when i go and try to test is using below query. I do see everything. What my query did actually? Am I doing it right?
SELECT name FROM [Scorecard].sys.objects WHERE type = 'u'and name like '%JKL%'
Any help will be appreciated. Thanks.
Try this version of your script:-
DECLARE
#LoopId int,
#Command varchar(500),
#tblName varchar(100),
#dbName sysname
DECLARE #List TABLE
(
DBName sysname not null,
TableName sysname not null,
LoopId int not null identity(1,1)
)
-- Load with tables you wish to drop
INSERT #List (DBName, TableName)
SELECT 'Morgage',name FROM [Morgage].sys.objects WHERE type = 'u' and name like '%JKL%'
UNION
SELECT 'Scorecard',name FROM [Scorecard].sys.objects WHERE type = 'u'and name like '%JKL%'
UNION
SELECT 'Core',name FROM [Core].sys.objects WHERE type = 'u' and name like '%JKL%'
SET #LoopId = ##rowcount
-- Go through list and process each item
WHILE #LoopId > 0
BEGIN
SELECT #tblName = TableName, #dbName=DBName from #List where LoopId = #LoopId
SET #Command = 'USE ' + #dbName + ';if not exists(select 1 from sys.foreign_keys where parent_object_id=object_id(''' + #tblName + ''',''U'')' + char(10) + 'Drop table ' + #tblName + ';'
execute (#Command)
SET #LoopId = #LoopId - 1
END
Might be the queries are not committing by default. Try specify it explicitly

how to use openrowset to execute a stored procedure with parameters

I'm creating a stored procedure which gets some parameters and in turn these parameters are sent to another stored procedure which I'm calling from openrowset but I'm getting some syntax errors.
CREATE PROCEDURE UpdatePrevFYConfigData
-- Add the parameters for the stored procedure here
#startDate datetime,
#endDate datetime,
#productGroup varchar(8000) = 'All',
#projectType varchar(500) = 'All',
#businessUnit nvarchar(50) = 'All',
#developmentLocation nvarchar(100) = 'All'
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #start varchar(50)
declare #end varchar(50)
set #start = cast(#startDate as varchar(40))
set #end = cast(#endDate as varchar(40))
-- Insert statements for procedure here
select round(avg(a.DeviationDeadline),2) as DeviationDeadline,
round(avg(a.DeviationDefinition),2) as DeviationDefinition,
round(avg(a.DeviationRDCosts),2) as DeviationRDCosts,
round(avg(a.FunctionsAdded) + avg(a.FunctionsDeleted),2) as NotRealizedFuncs,
round(avg(a.DeviationPM2000Aufwand),2) as DeviationPM200Aufwand,
round(avg(b.Defect),2) as Defect
into #tempTable
from openrowset('SQLNCLI',
'Server=.\sqlexpress;Trusted_Connection=yes;',
'SET NOCOUNT ON;SET FMTONLY OFF;EXEC [BSC_DB].dbo.SelectScorecardGraphData
'''+#start+''',
'''+#end+''',
'''+#productGroup+''',
'''+#projectType+''',
''1'',
''0'',
''All'',
''Current'',
'''+#businessUnit+''',
'''+#developmentLocation+'''
') as a,
openrowset('SQLNCLI', 'Server=.\sqlexpress;Trusted_Connection=yes;', 'SET NOCOUNT ON;SET FMTONLY OFF;EXEC [BSC_DB].dbo.GetSPCDefectDistributionData
'''+cast(#startDate as varchar(40))+''',
'''+cast(#endDate as varchar(40))+''',
''Defect'',
'''+#projectType+''',
'''+#productGroup+''',
'''+#businessUnit+''',
'''+#developmentLocation+'''') as b
update dbo.EA_ProcessScorecard_Config_Tbl
set EPC_Deviation = case EPC_Metric
when 'PM200' then (select DeviationDefinition from #tempTable)
when 'PM300' then (select DeviationDeadline from #tempTable)
when 'Cost' then (select DeviationRDCosts from #tempTable)
when 'PM150' then (select DeviationPM200Aufwand from #tempTable)
when 'Defect' then (select Defect from #tempTable)
when 'Funcs' then (select NotRealizedFuncs from #tempTable)
END
where EPC_Description = 'PrevFY' and EPC_FYYear = '0'
drop table #tempTable
END
GO
I'm not able to create it and I get the error message:
Msg 102, Level 15, State 1, Procedure UpdatePrevFYConfigData,
Line 38 Incorrect syntax near '+'.
... but if I use hard coded values for the parameters it works!!
Please help!
Both OPENROWSET and OPENDATASOURCE should be used only for accessing external data for, let's say, quick and dirty solutions, or when it is not possible to configure a permanent linked server. These functions do not provide all of the functionality available from a linked server.
The arguments of OPENROWSET and OPENDATASOURCE do not support variables. They have to be specified as string-literal. If variables need to be passed in as arguments to these functions, a query string containing these variables can be constructed dynamically and executed using the EXEC statement.
Similar to (not syntax checked)
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT *
FROM OPENROWSET(''SQLNCLI'',''server=.\sqlexpress;Trusted_Connection=yes'',''SET NOCOUNT ON;SET FMTONLY OFF;EXEC [BSC_DB].dbo.SelectScorecardGraphData ''''' + cast(#param1 as varchar(10)) + ''''',''' + cast(#param2 as varchar(n)) ''')'
EXEC #sqlCommand
And so on...
Hope that helps. Kind regards,
Stefan
-- FOR USING OPENROWSETS
EXEC sp_configure 'Ad Hoc Distributed Queries'
,1
RECONFIGURE
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT INTO #TABLESIZESYEAR SELECT NULL AS [TABLE NAME], * FROM OPENROWSET
(''SQLOLEDB'',''Server=(local);TRUSTED_CONNECTION=YES;'',''set fmtonly off EXEC one.[dbo].[InvestigateDataGrowthByYearAndClient] #pDATECOLUMN =' + #YEARCOLUMN + ' ,
#pTABLENAME = ' + #TABLENAME + ' WITH RESULT SETS(
([YEAR NAME] NVARCHAR(5) NULL
, [NUMBER OF ROWS] CHAR(11)
, [RESERVED SPACE] VARCHAR(18)
, [DATA SPACE] VARCHAR(18)
, [INDEX SIZE] VARCHAR(18)
, [UNUSED SPACE] VARCHAR(18) )
)
;'') '
DECLARE #ParmDefinition NVARCHAR(500) = '#pDATECOLUMN NVARCHAR(20)
,#YEARCOLUMN NVARCHAR(20)
,#pTABLENAME NVARCHAR(60)';
EXECUTE sp_executesql #sql
,#ParmDefinition
,#YEARCOLUMN = #YEARCOLUMN
,#pDATECOLUMN = #YEARCOLUMN
,#pTABLENAME = #TABLENAME