Cannot correctly declare variable in procedure loop - mysql

This is driving me bananas. I'm not a mysql guru by any stretch. My goal is to add a large number of columns to a table. I've tried this several ways and the procedure chokes on the DECLARE #FooA NVARCHAR(MAX);. No clue as to why.
I appreciate any pointers...
USE mydatabase;
DELIMITER $$
DROP PROCEDURE IF EXISTS RepeatLoopProc$$
CREATE PROCEDURE RepeatLoopProc()
BEGIN
DECLARE x INT;
DECLARE sn VARCHAR(30);
DECLARE dr VARCHAR(48);
DECLARE #FooA NVARCHAR(MAX);
SET x = 0;
WHILE (x <= 150) DO
SET sn = CONCAT('drivesn_', x);
SET dr = CONCAT('driveinf_', x);
SET x = x + 1;
SET #FooA = 'ALTER TABLE DRIVE_MASTER ADD ' + sn + ' VARCHAR(30), ADD ' + dr + ' VARCHAR(48)';
EXEC sp_executesql #FooA;
END WHILE;
END$$
DELIMITER ;
When I do this I get:
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 '#FooA NVARCHAR(MAX);
My forehead is getting flat from slamming it into my desk.
The ultimate goal is adding columns drivesn_0, driveinf_0, drivesn_1, driveinf_1, etc all the way out to drivesn_150 and driveinf_150. Type VARCHAR(30) and VARCHAR(48) for each respectively.

#variables are not DECLAREd and declared variables' identifiers do not start with #.
Also, ALTER statements typically recreate a table behind the scenes (equivalent to something like CREATE TABLE newversion... INSERT INTO newversion SELECT * FROM oldversion ... DROP TABLE oldversion ... RENAME newversion). So you'd be much better off building up a single ALTER statement within the loop, and executing it only once.
Example:
...
SET #FooA = 'ALTER TABLE DRIVE_MASTER';
SET x = 0;
WHILE (x <= 150) DO
SET sn = CONCAT('drivesn_', x);
SET dr = CONCAT('driveinf_', x);
SET #FooA = CONCAT(#FooA
, CASE WHEN x != 0 THEN ', ' ELSE '' END
, 'ADD ', sn, ' VARCHAR(30), ADD ', dr, ' VARCHAR(48)'
);
SET x = x + 1;
END WHILE;
EXEC sp_executesql #FooA;
...
... but what Barmar said in comments is good advice, you should probably just have another table, something like DRIVE_MASTER_DETAILS(x int, sn VARCHAR(30), dr VARCHAR(48))

I already have multiple tables. Basically I am using this to catalog drive serial numbers in hosts. Host can have up to 150 drives. Other tables contain network interface information (macaddrs, etc). All tied together by a common index value. For a system with 150 disk drives I cannot see another way other than 150 columns. Either that or I am missing a fundamental concept.

Related

Mysql - Return table from stored procedure into a variable?

Thanks to this answer https://stackoverflow.com/a/8180159/16349298 , i'm able to translate
a string into a temporary table (usable for WHERE <id> IN <tmpTable>.<colomn>)
The only modification i made is at the end (The select) :
CREATE PROCEDURE stringToTmpTable(IN inputString VARCHAR(255), IN sep VARCHAR(255))
BEGIN
declare pos int; -- Keeping track of the next item's position
declare item varchar(100); -- A single item of the input
declare breaker int; -- Safeguard for while loop
-- The string must end with the delimiter
if right(inputString, 1) <> sep then
set inputString = concat(inputString, sep);
end if;
DROP TABLE IF EXISTS MyTemporaryTable;
CREATE TEMPORARY TABLE MyTemporaryTable ( columnName varchar(100) );
set breaker = 0;
while (breaker < 2000) && (length(inputString) > 1) do
-- Iterate looking for the delimiter, add rows to temporary table.
set breaker = breaker + 1;
set pos = INSTR(inputString, sep);
set item = LEFT(inputString, pos - 1);
set inputString = substring(inputString, pos + 1);
insert into MyTemporaryTable values(item);
end while;
SELECT * FROM MyTemporaryTable;
END
I would like to use this process in a function or procedure in order to call it in any procedure that needs it.
So here is the problem :
I don't know how to store the result of this procedure into a variable : i can't use the SELECT * INTO #p FROM ...; like CALL stringToTmpTable(<string>,<separator>) INTO #table;
An other way would be to add OUT parameter to stringToTmpTable() but it can't return multiple rows. Unfortunatly the amount of parameters in the string is variable so i can't define as much variable as there is parameters in the string.
Finally the FIND_IN_SET() isn't the solution i need.
In the worst case I could copy / past the stringToTmpTable() process in any other procedure that needs it, but that doesn't seem like the best way to me.
Any suggestions ?
"i'm able to translate a string into a temporary table" too, but I am using a different method:
SET #input = 'Banana, Apple, Orange, Pears';
WITH RECURSIVE cte1 as (
select
#input as s,
substring_index(substring_index(#input,',',1),',',-1) as w,
length(#input)-length(replace(#input,',','')) x
union all
select
substring_index(s,',',-x),
trim(substring_index(substring_index(substring_index(s,',',-x),',',1),',',-1)) as w,
x-1 x
from cte1 where s<>'' and x>0
)
select * from cte1
DBFIDDLE
But it's a bit of a problem to determine the real problem you have, which is causing you to ask this question. So this is not an answer, but just a different way of selecting all words from a comma-delimted string.

Should it be possible to execute an SQL function in a check constraint within DB2 z/OS

Simple version of the DDL:
create function rm00dv1.no_concurrent_schedules()
returns integer
LANGUAGE SQL
READS SQL DATA
NO EXTERNAL ACTION
NOT DETERMINISTIC
BEGIN
declare num_overlaps integer;
select count(*)
into num_overlaps
from
rm00dv1.schedules a
where
a.id != 0
and
exists (
select 1
from rm00dv1.schedules b
where
b.id = 0 -- matches the key of a given record
and rm00dv1.isConcurrent(b.schdl_eff_dt, b.schdl_trm_dt, a.schdl_eff_dt, a.schdl_trm_dt) != 0
);
return num_overlaps;
end;
Table:
create table rm00dv1.schedules (
id int not null,
schdl_eff_dt date not null,
schdl_trm_dt date not null,
info_chg_ts timestamp(6) not null with default
)
in RM00DV1.TSRMDV01 ;
alter table rm00dv1.schedules add constraint no_schedule_overlap
check ((schdl_trm_dt < '01/01/2015')
or
rm00dv1.no_concurrent_schedules() <= 0);
I am getting an SQL00551N - no execution privilege and that is odd because I can execute the function in a select statement.
Any idea to solve this problem?
Thanks.
Looks like you can't. I'm looking at the DB2 10 for z/OS reference for ALTER TABLE reference and it says the following under CHECK (check-condition): "A check-condition is a search condition, with the following restrictions: ... must not contain... Built-in or user-defined functions...".
Since your function looks like it won't convert to a check condition, defining triggers on the table might be the next best option.
I learned that AFTER triggers do not get a -746 like BEFORE triggers do. I had really wanted to use a CONSTRAINT because that best captures the intent for people who come after me, with a BEFORE trigger to terminate the active schedules. But, it looks like a sequence of triggers is going to be the way to go. It is a bit clunky because the triggers all have to be created separately and you have to look at them together to get the intent, and because correct behavior is dependent on their creation order. Yes, it is documented that they will be executed in the order of their creation.
Happy path termination of rows without a specified termination date:
CREATE TRIGGER terminate_no_trm
after
INSERT ON schedules
referencing new as new
FOR EACH ROW
MODE DB2SQL
BEGIN ATOMIC
update schedules
set
schdl_trm_dt = max(schdl_eff_dt, new.schdl_eff_dt - 1 days) -- prob not necessary, but don't set the trm before the eff
, info_chg_ts = new.info_chg_ts
where
new.keyCombo = keyCombo
and
schdl_trm_dt = '9999-12-31'
and schdl_eff_dt < new.schdl_eff_dt;
end
Prevent insert of rows if that insert causes an overlap:
CREATE TRIGGER no_overlapping_schedules_i
after
insert ON schedules
referencing new as n
FOR EACH ROW
MODE DB2SQL
when (num_concurrent_schedules(n.keyCombo) > 0)
begin atomic
SIGNAL SQLSTATE '75001' (
'Concurrent schedules detected: '
concat ' ' concat cast(n.keyCombo as varchar(32))
concat ': ' concat cast(n.schdl_eff_dt as varchar(32))
concat ' to ' concat cast(n.schdl_trm_dt as varchar(32))
);
end
and prevent UPDATE if that would result in an overlap
CREATE TRIGGER no_overlapping_schedules_u
after
update ON schedules
referencing new as n
FOR EACH ROW
MODE DB2SQL
when (num_concurrent_schedules(n.keyCombo) > 0)
begin atomic
SIGNAL SQLSTATE '75001' (
'Concurrent schedules detected: '
concat ' ' concat cast(n.keyCombo as varchar(32))
concat ': ' concat cast(n.schdl_eff_dt as varchar(32))
concat ' to ' concat cast(n.schdl_trm_dt as varchar(32))
);
end
Thanks for the ideas.

Check to see if tables are present in a database - stored procedure - MySQL

I want the user to input whatever database they want to check and whatever tables they want to check. For example the call would look like this:
call tableCheck('MyDatabase', 'table1 table20 table3')
So the procedure would check for those tables (space delimited). I have my code down below but I am having problem checking the other tables, it reads the first but not the second or third one. SO my code is not looping or not reading the next word.
PROCEDURE `tableCheck` (db VARCHAR(256), db_tables VARCHAR(256))
BEGIN
DECLARE tbl, tbls VARCHAR(256);
DECLARE c INT DEFAULT 0;
SET tbls = db_tables;
WHILE c = 0 DO
#split word
SET tbl = SUBSTRING_INDEX(tbls," ",1);
#go to next string
SET tbls = SUBSTR(tbls,LENGTH(tbl)+1);
#check every table
SELECT table_name AS 'Table Name'
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema=db AND table_name=tbl;
IF tbls = 0 THEN
SET c = 1;
END IF;
END WHILE;
END
I have given this link out a few times today...so maybe it will work for you too.
Convert a delimited string to a list of values
Using the dbo.fnArray function from that link you should be able to join on the INFORMATION_SCHEMA.TABLES like this:
create procedure dbo.spCheckTable #db varchar(256), #tbls varchar(8000)
as
begin
select *
from INFORMATION_SCHEMA.TABLES i
inner join dbo.fnArray(#tbls, ' ') t on i.TABLE_NAME = t.arrValue
where i.TABLE_CATALOG = #db
end
Now its a stored procedure

What's wrong with the stored procedure

I have a table called Std_Components which acts like an index for list of components with associated tables. The column AssociatedTable holds the name of table that actually contains the component data.
Please check images below -
Here is table data for Std_SteeringPumps
I am trying to create a stored procedure that will copy Std_Components table as well as all associated tables with new name. For ex. Lets say if i provided 001 as a parameter to this stored procedure i should be able create new tables like C001_Components, C001_SteeringPumps and so on.
This is what I have done so far:
ALTER PROCEDURE [dbo].[sgi_sp_CreateTablesForNewCompany]
-- Add the parameters for the stored procedure here
#CompanyId varchar(5)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- declare variables
declare #qry as varchar(2000)
declare #compTblName as varchar(100)
set #compTblName = 'C'+#companyId +'_Components'
-- Check if table already exists
IF object_id(#compTblName) is not null
return
-- Create main component index table by copying standard component table --
set #qry = 'Select * into '+#compTblName+' From Std_Components;';
--print #qry
--execute (#qry)
set #qry =#qry + 'Update C'+#companyId +'_Components Set AssociatedTable=''C'+#companyId +'''+substring(AssociatedTable,4,200);';
--print #qry
--exec #qry
-- Create all child tables --
Select * Into #TempTbl From dbo.Std_Components
Declare #Id int
While (Select Count(*) From #TempTbl) > 0
Begin
declare #rowTableName as varchar(50)
declare #compNewTbl as varchar(50)
Select Top 1 #rowTableName=AssociatedTable, #Id = Id From #TempTbl
set #compNewTbl = 'C'+#companyId + substring(#rowTableName,4,200);
set #qry = #qry + 'Select * into '+#compNewTbl+' From ' + #rowTableName + ';'
--print #qry
--exec #qry
Delete #TempTbl Where Id = #Id
End
print #qry
exec #qry
END
Here is the output of the print statement for the query it generates -
Select * into C001_Components From Std_Components;
Update C001_Components Set AssociatedTable='C001'+substring(AssociatedTable,4,200);
Select * into C001_SteeringPumps From Std_SteeringPumps;
But when the stored procedure is executed, I get the following error -
Msg 203, Level 16, State 2, Procedure sgi_sp_CreateTablesForNewCompany, Line 56
The name 'Select * into C001_Components From Std_Components;Update C001_Components Set AssociatedTable='C001'+substring(AssociatedTable,4,200);Select * into C001_SteeringPumps From Std_SteeringPumps;' is not a valid identifier.
Can anybody help me out resolve this issue.
Thanks for sharing your time and wisdom.
The error you're getting is because the EXEC statement (the last line of the stored procedure) needs to have brackets around the #qry variable so that it becomes
exec(#qry)
Without the brackets it's treating the entire SQL string as stored procedure name.
The non valid indentifier is around the AssociatedTable part
Set AssociatedTable='C001'+substring(AssociatedTable,4,200); will not run as there is no scope for AssociatedTable to substring - the string needs to contain the name of the table completely to be able to be executed
Instead of
exec #qry;
You need
exec sp_executesql #qry;
You'll also need to change the type of #qry to NVARCHAR. Note that because of the dynamic sql, the proc is prone to SQL Injection and other escaping issues (i.e. ensure that #CompanyId is validated)

Use MySql function variables as table name in the query

I need to have a function that increments the certain ID in a table (like auto_increment)
I have smth like this
DELIMITER $$
DROP FUNCTION IF EXISTS `GetNextID`$$
CREATE FUNCTION `GetNextID`(tblName TEXT, increment INT)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE NextID INT;
SELECT MAX(concat(tblName, 'ID')) + increment INTO NextID FROM concat('table_', tblName);
## SELECT MAX(articleID) + increment INTO NextID FROM table_article;
RETURN NextID;
END$$
DELIMITER ;
INSERT INTO `table_article` ( articleID, articleAlias ) VALUES ( GetNextID('article', 5), 'TEST' );
So i pass two variables: tblName (without table_ prefix), and the increment number. The commented line - SELECT query inside the function itself - works well, but i want to dynamically pass table name to the function and so get data from a certain col of certain table. What am I doing wrong?
The error is:
#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 '('table_', tblName);
RETURN NextID;
END' at line 6
if i simply try to select max value in such a way
SELECT MAX(articleID) + increment INTO NextID FROM tblName;
The error reports that tblName does not exist. How can i tell MySql that this is actually a var passed to the function, not an exact table name? If it is possible.
you need something like
prepare stmp from concat('SELECT MAX(ID) + ', increment, ' INTO NextID FROM table_', tblName);
execute stmp;
deallocate prepare stmp;