I have a SQL Server 2008 database instance for a cloud product that I manage product versions for.
We format the use is
customername_bt
customername_bs
where [_bt] is product 1 and [_bs] is product 2. I realise I can hard code then union a query like so;
select * from cust1_bt.dbo.version union
select * from cust1_bs.dbo.version union
select * from cust2_bt.dbo.version union
select * from cust2_bs.dbo.version
However, every time a new customer is added I'd have to revisit the query which adds an element of human error therefore, I'm wondering if I can achieve this result another way.
Obvious this isn't a thing but hopefully it drives what I'm hoping to achieve home
select * from '%_bt'.dbo.Version UNION
select * from '%_bs'.dbo.Version
Thanks in advance
You can use dynamic sql
DECLARE #SQLText VARCHAR(MAX) =''
select #SQLText = #SQLText + 'UNION select * from ' + QUOTENAME(name) + '.dbo.Version '
from sys.databases WHERE
name like '%[_]bt'
or name like '%[_]bs'
SET #SQLText = STUFF(#SQLText,1,6,'')
EXEC #SQLText
Related
I have multiple tables i.e. jibs3_posts, jibs4_posts, jibs5_posts.. and so on. Is there any way I could make a join between all these tables with some sort of wildcard for the jibs-prefix?
For example:
SELECT * FROM 'jibs*_posts';
P.S. Sorry if this is a duplicate, but couldn't find any solution.
P.P.S This is a WordPress Multisite
1- Get your table names:
declare #row_number int = 0;
CREATE TEMPORARY TABLE JibsTables (table_name varchar(50), num int)
INSERT INTO JibsTables (table_name, num)
SELECT table_name, (#row_number:=#row_number + 1) AS num
FROM information_schema.tables
WHERE table_schema='your_database_name'
AND table_name like 'jibs%'
2- Create dynamic query in a loop.
declare #counter = 1
declare #sql nvarchar(max);
declare #temptable nvarchar(100);
declare #limit int = (select count(*) from JibsTables)
while #counter <= #limit
begin
set #temptable = select table_name from JibsTables where num = #counter
if #counter <> #limit
begin
set #sql = #sql + ' select * from ' + #temptable + ' union'
end
else
begin
set #sql = #sql + ' select * from ' + #temptable + ';'
end
set #counter = #counter + 1
end
3- Execute your dynamic query
PREPARE stmt1 FROM #sql
EXECUTE stmt1
DEALLOCATE PREPARE stmt1;
I am familiar with the MSSQL syntax, tried my best to find the correct syntax for mysql, but logic is clear I believe. Hope all is good, please let me know.
Another alternative. If new jibs tables aren't being added too frequently, you could create a view that UNIONs all of them together, then write your queries against the view. That way, you only need to do the tedious typing once.
If memory serves (it's been a while since I played around in a Wordpress site) you should be able to add the necessary object to the database.
Something to the effect of:
CREATE VIEW v_jibs_posts AS
SELECT <column_list> FROM jibs1_posts
UNION
...<SELECTS from all the tables>
UNION
SELECT <column_list> FROM jibs<n>_posts
Then just add an additional UNION to the view as new tables are created by the app.
Of course, if they're popping up frequently, this would be too cumbersome to maintain.
Edit: If you wanted to get fancy, you could use Eray Balkanli's dynamic SQL to generate an ALTER VIEW statement to pick up new tables, and then schedule that to run periodically.
You could do something like this
SHOW TABLES LIKE 'jibs%_posts';
this will list all the tables with that naming scheme.
Then you can concatenate all the tables (if they have the same number of columns) with a UNION
SELECT * FROM jibs_posts
UNION
// ... more SELECTS
UNION
SELECT * FROM jibsX_posts;
This is not possible with SQL, but there are alternative approaches.
If there is a good reason to abandon the multiple tables (i.e., if the data model would be satisfied by one, common table), you can pursue a one-time conversion from the multiple tables into a single table.
If there is a good reason to retain the multiple tables (i.e., if there is something about your data model, or some logistical constraint, that dictates such an arrangement), then this is a good situation for combining tools. Specifically, you can use your favorite programming or scripting language to generate the SQL that references all of the tables, then employ that generated SQL.
Many programming languages would allow you to both generate the SQL and utilize it in the same program, through database bindings.
EDIT : I see that you've added the wordpress tag (I began composing my answer before it was there), so I'm not sure how much my answer applies. That is to say, I'm not sure how much access you have to interact directly with the database. If you are constrained by what Wordpress requires and/or the manner in which Wordpress allows you to run the SQL you are wanting to run, then my generic MySQL / SQL answer might not be much help.
Still, my general advice would be to approach the problem with all the tools you have in your toolbox, and consider a combination-of-strengths approach, since SQL does not support wildcards for table names.
SELECT #sqlText = #sqlText + ' SELECT * FROM ' + QUOTENAME(name) + CHAR(13) FROM sys.tables
If you are using phpmyadmin do the following steps:
1) select the database
2) Select search from the top links
3) Now you will get text box to enter what to search
4) Select the table in which you want to search.
It will search whole database get the result
You can't search like that. You can write a query as
SELECT * FROM tablename
WHERE MATCH(`col1`, `col2`, `col3`) AGAINST ('$searchword')
I basically want to be able to take any non nested SQL string and convert it to the SQL to get the count all with the same regex.
It just has to be able to match anything between SELECT and FROM one time and replace with count(*) but I haven't allocated experience points to leveling up my regex yet.
i.e.
SELECT col1, col2 FROM my_table where..." to "SELECT count(*) FROM my_table where...
Or
SELECT * FROM my_table where..." to "SELECT count(*) FROM my_table where...
Why not just do
SELECT COUNT(*) from ( <insert original sql here> ) as X
For a regex, you could use a simple one demonstrated here.
Essentially we replace whatever is in between SELECT and FROM with COUNT(*). Details are at the link as well.
Note that this will assist you in your thinking but is no way tested in depth. Please run some tests on your own.
You could also use the link to generate code in Python, JavaScript etc.
Edit 1: the link was enclosed as a code snippet and so did not work. Removed the code meta tag.
I always believe regex should be used when you have no simpler or any option at all. In your case, you can do this with simple SQL logic instead of regex. You can pass the original query as-is to your MySQL procedure or whatever and do this:
set #inputQuery = 'SELECT col1, col2 FROM my_table where id = 1'; -- you will pass this
set #startIndex = locate('select', #inputQuery) + char_length(rtrim('select'));
set #endIndex = locate('where', #inputQuery);
set #subString = substring(#inputQuery, #startIndex, #endIndex - #startIndex);
set #finalQuery = replace(#inputQuery, #subString, ' count(*) ');
select #finalQuery;
Output:
SELECT count(*) where id = 1
In MySQL, you can use SQL_CALC_FOUND_ROWS and then FOUND_ROWS() with any query. So:
SELECT SQL_CALC_FOUND_ROWS . . .
FROM . . .
Then to get the number of rows:
SELECT FOUND_ROWS()
This is defined in the documentation.
I want to write following query in MySQL and keep getting errors. I have no idea what's wrong, everything seems fine by me.
Query:
SELECT
*
FROM
client
WHERE
id IN (
SELECT
client_id
FROM
url
WHERE
',1,2,' LIKE '%,' + CAST(url_type_id AS CHAR(50)) + ',%'
)
It must have got something to do with the "'%,' + " part, but I honestly don't get it
You have to use CONCAT() to join 2 strings not "+", here is the query which you looking for
SELECT *
FROM client
WHERE id IN ( SELECT client_id
FROM url
WHERE ',1,2,' LIKE CONCAT('%,', CAST(url_type_id AS CHAR(50)), ',%')
)
It is very bad idea creating lots of tables in single database. I understand it now.
So i want to fix this by creating new single table. so i want to fetch all rows of all tables into single table.
I searched everywhere but there isn't a solution, so need help
Here is my Situation:
Each table has following columns
id
name
flag
poststatus
I can run below query to get data from two tables:
SELECT * FROM table1 WHERE poststatus = '2' UNION SELECT * FROM table2 WHERE poststatus = '2';
But this is for only two tables i have to run query for almost 5000 tables.
is there any better way to fetch all data in single query or any other idea ..
Thank you.
If you have PHP at hand (like the tag suggests) you can create a small script that creates all the 5000 SELECT statements for you like:
for($i=1;$i<=5000;$i++)
$sql.="INSERT INTO combined (name, flag, poststatus) SELECT name, flag, poststatus FROM table".$i." WHERE poststatus=2\n";
file_put_contents('combine.sql', $sql);
poststatus = '2';
Execute replacing the schema and the like expression.
set group_concat_max_len = 1048576;
select
concat('select * from ',
group_concat(table_name separator ' where poststatus = ''2'' union select * from ')
) as query
from information_schema.tables
where table_schema = 'database_name' and table_name like 'table%'