COLUMN SELECTION and VARIABLE ASSIGNMENT in single select - mysql

I can assign value to variable and select column in single statement in MySQL like this
declare #i int= 0
select #i :=1 , col1 FROM Table
But can not do that in SQL SERVER.
As it gives the error
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
Please describe what is the underlying difference.

Related

options for creating sproc variable in mysql?

I have a sproc with multiple selects and result sets. The last query in the sproc needs to select data where a table created date >= the first day of the current month. I have SQL which successfully returns the first day of the month as expected. I need to select this value into a sproc variable FirstDayOfTheMonth and then reference this variable in the WHERE clause of the subsequent SELECT statement in the sproc. I included the following SQL before the final result set in the sproc but it seems that MySQL doesn't like something about it - something about its structure, positioning or syntax:
DECLARE FirstDayOfMonth INT DEFAULT 0;
SET FirstDayOfMonth = (SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))- 1 DAY)
How can I update my existing attempt at a MySQL sproc variable so that my sproc compiles successfully with this variable declaration?
UPDATE
I tried to put the following 2 lines immediately after the BEGIN keyword in my sproc:
DECLARE FirstDayOfMonth INT DEFAULT 0;
SET FirstDayOfMonth = (SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))- 1 DAY)
MySQL Workbench displays an error on the SET statement:
FirstDayOfMonth is not valid at this position, expecting an identifier
Any idea what I need to do differently here?
The DECLARE-statements need to be in the beginning of the procedure, before anything else, just after the BEGIN.

OPENROWSET with no column alias?

I'm trying to write a query to select the results of a stored procedure into a temp table. However the stored procedure has been set up so that when it runs its returns 1 result with no alias. (See below)
obviously I get an error when I try and select the data into a temp table.
An object or column name is missing or empty. For SELECT INTO
statements, verify each column has a name. For other statements, look
for empty alias names. Aliases defined as "" or [] are not allowed.
Change the alias to a valid name.
Is there any way round this as I will be unable to update the procedure to output an alias! Basically Im after a way of doing a
SELECT * INTO #tmptable
FROM OPENROWSET ('SQLNCLI', 'Server=ServerName;Trusted_Connection=yes;','SET FMTONLY OFF EXEC sp_name')
If you know how many columns you will get back from the OPENROWSET, then you can create the temporary table before inserting values; this allows you to give the columns a name.
CREATE TABLE #tmptable (Value INT NOT NULL)
INSERT #tmptable
SELECT * FROM OPENROWSET ('SQLNCLI','Server=ServerName;Trusted_Connection=yes;','SET FMTONLY OFF EXEC sp_name')
-- DROP TABLE #tmptable
If you do not know how many columns you are returning... I do not know that it is possible.

how to set variables variables in mysql

I tried setting a variable in sql as follows:
DECLARE #fromDate VARCHAR(60);
SET #fromDate = '2013-01-01 00:00:00';
SET #toDate = '2013-02-01 00:00:00';
SELECT #fromDate;
but this is not working.
what am I doing incorrectly?
You don't DECLARE variables that start with #.
MySQL has two different types of variables. One is a session variable, with the # prefix. The other type is the local variable inside a trigger or stored proc.
The DECLARE statement is valid only inside of body of stored procedure or function, and this variables don't start by #.
The variables that start with # don't need DECLARE, just use outside of stored procedure inclusive.
First lets take a look at how can we define a variable in mysql
To define a varible in mysql it should start with '#' like #{variable_name} and this '{variable_name}', we can replace it with our variable name.
Now, how to assign a value in a variable in mysql. For this we have many ways to do that
Using keyword 'SET'.
Example :- mysql > SET #a = 1;
Without using keyword 'SET' and using ':='.
Example:- mysql > #a:=1;
By using 'SELECT' statement.
Example:- mysql > select 1 into #a;
Here #a is user defined variable and 1 is going to be assigned in #a.
Now how to get or select the value of #{variable_name}.
we can use select statement like
Example :-
mysql > select #a;
it will show the output and show the value of #a.
Now how to assign a value from a table in a variable.
For this we can use two statement like :-
#a := (select emp_name from employee where emp_id = 1);
select emp_name into #a from employee where emp_id = 1;
Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.
refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql

MySQL - Result consisted of more than one row

I am a MySQL rookie and have been trying to create a stored procedure. The code below returns the error Error Code: 1172. Result consisted of more than one row. What am I doing wrong? (I'm using MySQL workbench)
CREATE DEFINER=`root`#`localhost` PROCEDURE `season_private_league_user`(
IN user_id INT,
OUT league_name VARCHAR(25),
OUT host_user VARCHAR(30))
BEGIN
DECLARE userteamid INT;
DECLARE var_league_name VARCHAR(25);
DECLARE var_host_user VARCHAR(30);
# Retrieve user team from user_id
SELECT CS_USER_TEAMS_ID INTO userteamid
FROM classicseasonmodel_classicseasonuserteam
WHERE user_id = user_id;
#LEAGUE NAME
SELECT classicseasonmodel_classicseasonprivateleague.private_league_name INTO var_league_name
FROM classicseasonmodel_classicseasonuserteamprivateleague
INNER JOIN classicseasonmodel_classicseasonprivateleague
ON classicseasonmodel_classicseasonuserteamprivateleague.private_league_id=classicseasonmodel_classicseasonprivateleague.CS_PRIVATE_LEAGUE_ID
WHERE user_team_id = userteamid;
#HOST_USER
SELECT classicseasonmodel_classicseasonprivateleague.host_user_id INTO var_host_user
FROM classicseasonmodel_classicseasonuserteamprivateleague
INNER JOIN classicseasonmodel_classicseasonprivateleague
ON classicseasonmodel_classicseasonuserteamprivateleague.private_league_id=classicseasonmodel_classicseasonprivateleague.CS_PRIVATE_LEAGUE_ID
WHERE user_team_id = userteamid;
SET league_name = var_league_name;
SET host_user = var_host_user;
END
CALL season_private_league_user(2, #league_name, #host_user);
SELECT #league_name AS league_name;
SELECT #host_user AS host_user;
Your column name and parameter name are identical. Rename your input parameter and change the command to this:
SELECT CS_USER_TEAMS_ID INTO userteamid
FROM classicseasonmodel_classicseasonuserteam
WHERE user_id = #user_id;
One of the SELECTs of you stored procedure that store the result in a variable returns more than one row, which returns in this error. This way you can only store single values in a variable, not multiple ones.
You can read about the SELECT...INTO statement here. The part that might be most interesting for you is:
The selected values are assigned to the variables. The number of
variables must match the number of columns. The query should return a
single row. If the query returns no rows, a warning with error code
1329 occurs (No data), and the variable values remain unchanged. If
the query returns multiple rows, error 1172 occurs (Result consisted
of more than one row). If it is possible that the statement may
retrieve multiple rows, you can use LIMIT 1 to limit the result set to
a single row.

How to check if a particular value exists in a variable which stores multiple value in mysql?

I am trying to create an sql trigger statement using phpmyadmin trigger interface.
Trying to do something for table 1 as shown below :
BEGIN
declare #valid_number int ;
select id into #valid_number from table 2 ;
if 10 does not exist in #valid_number then
{do something here}
end if;
END
how to achieve it?
First: a variable in a stored routine can't store multiple values, just a single one. Your statement
select id into #valid_number from table 2 ;
will only work, if the query returns exactly one row. An error will occur, if the query returns multiple rows, a warning, if the query returns no row at all, see the manual page to SELECT ... INTO:
The INTO clause can name a list of one or more variables, which can be
user-defined variables, stored procedure or function parameters, or
stored program local variables. [...]
The selected values are assigned to the variables. The number of
variables must match the number of columns. The query should return a
single row. If the query returns no rows, a warning with error code
1329 occurs (No data), and the variable values remain unchanged. If
the query returns multiple rows, error 1172 occurs (Result consisted
of more than one row).
Solution:
It's not difficult to create a statement that gives you the desired answer in exact one row, i.e.
SELECT COUNT(*) into valid_number FROM example WHERE id = 10;
This query will return 0, if the id 10 does not exists in column id and the count of occurences else. Of course there are several ways to achieve this, this is just one of them. You could rewrite your stored routine to:
BEGIN
-- prefer local variables, don't use user defined, if not needed.
DECLARE valid_number int;
SELECT COUNT(*) into valid_number FROM example WHERE id = 10;
IF valid_number = 0 THEN
-- do something here
END IF;
SELECT result;
END
Note
You could use a cursor to traverse the result of a query, but most times one wants to avoid a cursor. To use a cursor under similar conditions as of this question would not be the SQL way to do it and most times very inefficient.