I am very new in SQL. I just want to create basic trigger. It seems there might the problem about variable declaration or assignment.
DECLARE #i INT = 0
DECLARE #j INT = 0
DECLARE #player_name VARCHAR(255), #player_team VARCHAR(255);
DECLARE #absence_list_length = SELECT COUNT(*) FROM nhl_absence;
WHILE #i < 30
BEGIN
SET #player_name = SELECT playoff FROM `nhl_standings` where id like #i
SET #player_team = SELECT skr FROM `nhl_standings` where id like #j
WHILE #j < #absence_list_length
BEGIN
SELECT user FROM `nhl_absence` where name like #player_name;
UPDATE nhl_absence SET team = #player_team;
SET #j = #j + 1;
END
SET #player_team = SELECT skr FROM `nhl_standings` where id like #i
UPDATE nhl_standings SET team = #player_team;
SET #i = #i + 1;
END
Error message:
#1064 - Something is wrong in your syntax near 'DECLARE #i INT = 0 DECLARE #j INT = 0 DECLARE #player_name VARCHAR(255), #play' on line 1
If this is for MSSQL (Microsoft SQL Server), I think you need to declare and initialize the variable with 2 separate lines of code:
Instead of:
DECLARE #i INT = 0
Try:
DECLARE #i INT
SET #i = 0
See Variables (Transact-SQL) for details.
local variables at contrary of user variables doesnt allow #.
https://dev.mysql.com/doc/refman/8.0/en/declare-local-variable.html
Also you assign value using DEFAULT or SET
SQL DEMO
CREATE PROCEDURE simpleproc ()
BEGIN
DECLARE i INT DEFAULT 5;
DECLARE j INT DEFAULT 10;
DECLARE player_name VARCHAR(255) DEFAULT 'JHON';
DECLARE player_team VARCHAR(255) DEFAULT 'BRONCOS';
DECLARE absence_list_length INT;
SET absence_list_length = (SELECT 5);
SELECT i, j, player_name, player_team, absence_list_length;
END;
OUTPUT
I am having issues with a MySQL If statement that creates a group rank. here is the MySQL Statement:
SELECT EnCode, EnName, QuScore,
#scorerank := IF(#currathlete = EnCode, #scorerank + 1, 1),
#currathlete := EnCode
FROM ranking ORDER BY EnCode, QuScore DESC
It currently gives the following output
'1004277','Ashe','1628','1','1004277'
'1004277','Ashe','1309','1','1004277'
'1004277','Ashe','1263','1','1004277'
'1004277','Ashe','648','1','1004277'
'1004277','Ashe','645','1','1004277'
'1004277','Ashe','1628','1','1004277'
'1015934', 'Sabina', '544', '1', '1015934'
'1015934', 'Sabina', '455', '1', '1015934'
'1015934', 'Sabina', '276', '1', '1015934'
'1015934', 'Sabina', '216', '1', '1015934'
What it should be doing is incrementing each of the '1' numbers by one for each row that has the same code, and then starting from 1 again when it sees a different code number (1004277, then 1015934 in this case)
Any help is appreciated as i have followed a number of examples online using the above method but seem to hit the same issue a this point.
Try this way in stored Procedure:
drop PROCEDURE if EXISTS INCREMENTME;
create PROCEDURE INCREMENTME()
BEGIN
DECLARE OldEnNamevar VARCHAR(10) DEFAULT NULL;
DECLARE done INT DEFAULT FALSE;
DECLARE Encodevar VARCHAR(10);
DECLARE EnNamevar VARCHAR(10);
DECLARE QuScorevar VARCHAR(10);
DECLARE scorerankvar VARCHAR(10);
DECLARE currathalthletevar VARCHAR(10);
DECLARE countcode int(29) DEFAULT(1);
DECLARE counter int(20) default 0;
DECLARE get_cur CURSOR FOR select `Encode`,`EnName`,`QuScore`,`scorerank`,`currathalthlete` from tbl_ranking;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
drop table if exists temp_temptable;
create TEMPORARY table temp_temptable(Encodevar VARCHAR(50) NULL,EnNamevar VARCHAR(50) NULL,QuScorevar VARCHAR(50) NULL,scorerankvar VARCHAR(50) NULL,currathalthletevar VARCHAR(50) NULL,recordCount int(10) null);
OPEN get_cur;
REPEAT
set counter = counter + 1;
FETCH get_cur INTO Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar;
if (OldEnNamevar = EnNamevar) THEN
set countcode = countcode +1;
ELSE
if(counter=1) then
set countcode = 1;
ELSE
set countcode = 0;
end if;
end if;
if (OldEnNamevar != EnNamevar) THEN
set countcode = 1;
end if;
if(OldEnNamevar=NULL) then
set countcode = 1;
end if;
insert into temp_temptable (Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar,recordCount) values(Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar,countcode);
set OldEnNamevar = EnNamevar;
UNTIL done END REPEAT;
select * from temp_temptable;
drop temporary table if exists temp_temptable;
CLOSE get_cur;
END
call the procedure like this:
call INCREMENTME();
Here's the result:
You have to initialize your variables, otherwise they are null (at least at the beginning of the session, probably not anymore if you run it twice), and your query will give strange results. Try
SELECT EnCode, EnName, QuScore,
#scorerank := IF(#currathlete = EnCode, #scorerank + 1, 1),
#currathlete := EnCode
FROM ranking, (select #currathlete := '', #scorerank := 0) init
ORDER BY EnCode, QuScore DESC
I have to extract day, month and year of a date into variable and then do some updation on table
Problem I am having is that though i am able to get the result set by the local fields alway appear null
Mysql query is
DECLARE ExistingRecordYear INT;
DECLARE ExistingRecordMonth INT;
DECLARE ExistingRecordDay INT;
DECLARE CountRecords SMALLINT;
SELECT COUNT(*) , ExistingRecordYear = YEAR(updatedon),
ExistingRecordMonth = MONTH(updatedon), ExistingRecordDay = DAY(updatedon)
FROM `transactions`
WHERE `issuer_id` = _issuer_id
AND `msisdn` = _msisdn ;
Though updatedon is not a nullable field and my count result is 1 but i am still seeing null in all three fields of month,year,and day
Please help me in it
In a select statement, you use := to assign variables, not =. In addition, you probably want your variables to have a prefix to distinguish them from columns. Something like:
DECLARE v_ExistingRecordYear INT;
DECLARE v_ExistingRecordMonth INT;
DECLARE v_ExistingRecordDay INT;
DECLARE v_CountRecords SMALLINT;
SELECT v_CountRecords := COUNT(*) , v_ExistingRecordYear := YEAR(updatedon),
v_ExistingRecordMonth := MONTH(updatedon), v_ExistingRecordDay := DAY(updatedon)
FROM `transactions`
WHERE `issuer_id` = _issuer_id AND `msisdn` = _msisdn ;
I was wondering, if there is some way to shuffle the letters of a string in mysql/sql, i.e. something like the pseudocode: SELECT SHUFFLE('abcdef')?
Couldn't find any from http://dev.mysql.com/doc/refman/5.0/en/string-functions.html and searching for it just seems to find solutions for shuffling results, not a string.
Here you go:
DELIMITER //
DROP FUNCTION IF EXISTS shuffle //
CREATE FUNCTION shuffle(
v_chars TEXT
)
RETURNS TEXT
NOT DETERMINISTIC -- multiple RAND()'s
NO SQL
SQL SECURITY INVOKER
COMMENT ''
BEGIN
DECLARE v_retval TEXT DEFAULT '';
DECLARE u_pos INT UNSIGNED;
DECLARE u INT UNSIGNED;
SET u = LENGTH(v_chars);
WHILE u > 0
DO
SET u_pos = 1 + FLOOR(RAND() * u);
SET v_retval = CONCAT(v_retval, MID(v_chars, u_pos, 1));
SET v_chars = CONCAT(LEFT(v_chars, u_pos - 1), MID(v_chars, u_pos + 1, u));
SET u = u - 1;
END WHILE;
RETURN v_retval;
END;
//
DELIMITER ;
SELECT shuffle('abcdef');
See sqlfiddle.com for the output.
Tested successfully with mariadb 10.1 (mysql 5.6 equivalent)
Edit: this solution is for Microsoft SQL Server.
As it's not allowed to use RAND() in user defined function, we create a view to use it later in our shuffle function:
CREATE VIEW randomView
AS
SELECT RAND() randomResult
GO
The actual shuffle function is as following:
CREATE FUNCTION shuffle(#string NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) AS
BEGIN
DECLARE #pos INT
DECLARE #char CHAR(1)
DECLARE #shuffeld NVARCHAR(MAX)
DECLARE #random DECIMAL(18,18)
WHILE LEN(#string) > 0
BEGIN
SELECT #random = randomResult FROM randomView
SET #pos = (CONVERT(INT, #random*1000000) % LEN(#string)) + 1
SET #char = SUBSTRING(#string, #pos, 1)
SET #shuffeld = CONCAT(#shuffeld, #char)
SET #string = CONCAT(SUBSTRING(#string, 1, #pos-1), SUBSTRING(#string, #pos+1, LEN(#string)))
END
RETURN #shuffeld
END
Calling the function
DECLARE #string NVARCHAR(MAX) = 'abcdefghijklmnonpqrstuvwxyz0123456789!"ยง$%&/()='
SELECT dbo.shuffle(#string)
There is nothing in standard SQL - your best bet is probably to write a user defined function
How can I generate 5 unique random numbers?
Now I have something like
declare v_counter integer;
declare v_random integer;
declare v_result varchar(10);
select FLOOR(1+(rand()*50)) into v_result;
set v_counter=0;
while v_counter < 4 then
select FLOOR(1+(rand()*50)) into v_random;
set v_result = concat(v_result,'|',v_random;
v_counter = v_counter + 1;
end while;
The result can look like this:
12|22|3|46|3
The numbers need to be unique and sorted so it looks like:
1|2|3|4|5
Any idea?
If your range is small, and you have an integers table, a naive approach might work:
SELECT GROUP_CONCAT(i SEPARATOR '|')
FROM ( SELECT i
FROM ( SELECT i
FROM integers
WHERE i BETWEEN 1 AND 50
ORDER BY RAND()
LIMIT 5) sort_these_five
ORDER BY i) concat_these_five;