I want to have the query dynamically choose which table it looks up against based on a value in a particular row in another table.
I have this query:
SELECT d.name
FROM `database1`.domains AS d
WHERE (SELECT COUNT(u.id) FROM <<d.db_name>>.users u) > 0
I want to use the value of d.db_name as database name.
Example: d.db_name = database2
i want this:
SELECT d.name
FROM `database1`.domains AS d
WHERE (SELECT COUNT(u.id) FROM `database2`.users u) > 0
You could use variables for this:
SET #table_name = "some_table";
SELECT * FROM #table_name;
If you want to change the variable value depending on the results of your select you coudl use IF like this:
IF(some_column>50, #table_name := "value for true", #table_name := "value for false");
Related
example:
SET #numbers:= '1,2,3,4,5,6';
SELECT * FROM table WHERE t.number in (#numbers);
UPDATE table SET name = 'test' WHERE t.number in (#numbers);
How can I use the value of a variable in an IN statement? As in the request above
You can't use IN on a CSV string like that.
But you can use it with FIND_IN_SET
SET #numbers:= '1,2,3,4,5,6';
UPDATE your_table t
SET name = 'test'
WHERE FIND_IN_SET(t.number, #numbers) != 0;
SELECT *
FROM your_table t
WHERE FIND_IN_SET(t.number, #numbers) != 0;
In MySql 8 you could also unfold such CSV string as a JSON_TABLE.
And use that as a query for the IN.
SET #numbers:= '1,2,3,4,5,6';
UPDATE your_table t
SET name = 'test'
WHERE t.number IN (SELECT num FROM JSON_TABLE(CONCAT('[',#numbers,']'),'$[*]' COLUMNS(num INT PATH '$'))nums);
SELECT *
FROM your_table t
WHERE t.number IN (SELECT num FROM JSON_TABLE(CONCAT('[',#numbers,']'),'$[*]' COLUMNS(num INT PATH '$'))nums);
I wish to add data to the existing variable which I created in Mysql.
set #variable = select * from b where b.id = 35;
#variable = select * from b where b.name = "dheeraj";
How can I go ahead with this type of query.
set #variable := (select name.* from a)
set #variable := concat(#variable , ',' , select name.* from b)
I am still pretty new to SQL server and I am not sure how to do this. I am first creating a table with just the IDs I need:
SELECT DISTINCT
ID_NUMBER
INTO
#IDlist
FROM
V_Rpt_IDs WITH (NOLOCK)
WHERE
ID_NUMBER in (
'1000764169'
,'1005870537'
,'1008053856'
,'1008054376'
,'1008410224'
,'1008411317'
,'1008465318'
,'1008466074'
,'1008492967'
,'1010546872'
,'1010554301')
Select * from #IDlist
And this works fine. But now I would like to declare a variable to represent this column, or each item in this column, so that I can then do a loop where it loops through each ID Number and returns information about each one and then presents all of that as a table. Here is my shot at that:
Declare #IDNumber as VARCHAR(10)
Set #IDNumber = #IDlist.ID_NUMBER
DECLARE #cnt INT = 0
WHILE #cnt < (Select Count(*) From #IDlist)
BEGIN
SELECT TOP 1
NAME
,MAILING_ADDRESS_1
,MAILING_ADDRESS_CITY
,MAILING_STATE
,MAILING_ZIP
from
V_Rpt_Info
WHERE
ID_NUMBER = #IDNumber
SET #cnt = #cnt + 1
END
DROP TABLE #IDlist
But when I Set the #IDNumber variable to #IDlist.ID_NUMBER, it says The multi-part identifier "#IDlist.ID_NUMBER" could not be bound.
How do I do this?
Thanks
The way you set the variable is not correct, SQL doesn't know which ID_NUMBER row it should assign to the #IDNumber variable.
You should do this with a SELECT, for example
SET #IDNumber = SELECT TOP 1 ID_NUMBER FROM #IDlist
But, why would you like to loop through this temporary table this way ? Isn't it possible to join the necessary data with this table instead of doing it one by one ?
Rather then loop through, you're going to want to join your ID table to your V_Rpt_Info view.
SELECT
NAME
, MAILING_ADDRESS_1
, MAILING_ADDRESS_CITY
, MAILING_STATE
, MAILING_ZIP
FROM V_Rpt_Info V
INNER JOIN #IDlist ID
ON V.ID_NUMBER = ID.ID_NUMBER
Is there a way to make a value increment with every insert if having multiple inserts? (I dont speak of the primary key that autoincrements)
Lets say I have a structure like this:
|ID_PRODUCT|ID_CATEGORY|NAME|POSITION|
So I have individual product ids, each produt belongs to a category and has a different position in this category. I want to do something like this:
INSERT INTO products
( SELECT id_product, id_category, name, MY_POSITION++
FROM db2.products WHERE id_category = xxx )
So there should be a variable MY_POSITION that starts with 1 and increments every insert.
It would be really easy to do this all just with a scripting-language like php or python, but I want to get better with SQL :)
Yes: Use a user defined variable:
SET #position := 0; -- Define a variable
INSERT INTO products
SELECT id_product, id_category, name, (#position := #position + 1)
FROM db2.products
WHERE id_category = xxx;
The result of increment to #position is the value used for the insert.
Edit:
You can skip the declaration of the variable by handling the initial value in-line:
...
SELECT ..., (#position := ifnull(#position, 0) + 1)
...
This can be particularly handy when executing the query using a driver that does not allow multiple commands (separated by semicolons).
You will need to ORDER BY id_category and use two user variables so you can track the previous category id -
SET #position := 0;
SET #prev_cat := 0;
INSERT INTO products
SELECT id_product, id_category, name, position
FROM (
SELECT
id_product,
id_category,
name,
IF(#prev_cat = id_category, #position := #position + 1, #position := 1) AS position,
#prev_cat := id_category
FROM db2.products
ORDER BY id_category ASC, id_product ASC
) AS tmp;
This will allow you to do all categories in one query instead of category by category.
Purely to add to #Bohemians answer - I wanted the counter to reset every so often and this can be done like such:
SELECT *,(#position := IF (#position >= 15,1,#position + 1))
Where 15 is obviously the maximum number before reset.
Try setting a value using a subquery like this
(SELECT MAX(position) FROM products AS T2)+1
Or
(SELECT MAX(position) FROM products AS T2 WHERE id_category = 'product category')+1
Hope this will work.
update <tbl_name> set <column_name>=<column_name>+1 where <unique_column/s>='1'";
For those who are looking for example of update query, here it is:
SET #i := 0;
UPDATE products SET id = (#i := #i + 1);
Is it possible to set a user variable based on the result of a query in MySQL?
What I want to achieve is something like this (we can assume that both USER and GROUP are unique):
set #user = 123456;
set #group = select GROUP from USER where User = #user;
select * from USER where GROUP = #group;
Please note that I know it's possible but I do not wish to do this with nested queries.
Yes, but you need to move the variable assignment into the query:
SET #user := 123456;
SELECT #group := `group` FROM user WHERE user = #user;
SELECT * FROM user WHERE `group` = #group;
Test case:
CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);
Result:
SET #user := 123456;
SELECT #group := `group` FROM user WHERE user = #user;
SELECT * FROM user WHERE `group` = #group;
+--------+-------+
| user | group |
+--------+-------+
| 123456 | 5 |
| 111111 | 5 |
+--------+-------+
2 rows in set (0.00 sec)
Note that for SET, either = or := can be used as the assignment operator. However inside other statements, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements.
UPDATE:
Further to comments below, you may also do the following:
SET #user := 123456;
SELECT `group` FROM user LIMIT 1 INTO #group;
SELECT * FROM user WHERE `group` = #group;
Just add parenthesis around the query:
set #user = 123456;
set #group = (select GROUP from USER where User = #user);
select * from USER where GROUP = #group;
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 :-
1.
#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
Use this way so that result will not be displayed while running stored procedure.
The query:
SELECT a.strUserID
FROM tblUsers a
WHERE a.lngUserID = lngUserID
LIMIT 1
INTO #strUserID;