<pre class="c" name="code">建立一個database 叫ithelp
root[(none)]@localhost>create database ithelp;
Query OK, 1 row affected (0.02 sec)
root[(none)]@localhost>use ithelp;
Database changed
----------------------
建立三個A開頭的Table:
CREATE TABLE A01 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(10)
);
CREATE TABLE A02 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(10)
);
CREATE TABLE A03 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(10)
);
建立一個B開頭的Table:
CREATE TABLE B01 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(10)
);
輸入一些測試資料
INSERT INTO A01(NAME) VALUES
('A01'),('A01'),('A01');
INSERT INTO A02(NAME) VALUES
('A02'),('A02');
INSERT INTO A03(NAME) VALUES
('A03');
INSERT INTO B01(NAME) VALUES
('B01');
=============================
取出指定ithelp database 底下所有A開頭的Tables
SELECT table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'ithelp'
AND table_name LIKE 'A%';
+------------+
| table_name |
+------------+
| A01 |
| A02 |
| A03 |
+------------+
產生SQL Command:
SELECT CONCAT('SELECT NAME FROM ', table_name, ';') SQLCMD
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'ithelp'
AND table_name LIKE 'A%';
+-----------------------+
| SQLCMD |
+-----------------------+
| SELECT NAME FROM A01; |
| SELECT NAME FROM A02; |
| SELECT NAME FROM A03; |
+-----------------------+
以MySQL做例子,不過SQL Server也有information_schema,起個頭,接著自己變化吧
轉化了一下
<pre class="c" name="code">
create database ithelp
use ithelp
GO
CREATE TABLE A01 (
id INT NOT NULL IDENTITY (1, 1) PRIMARY KEY(id),
name VARCHAR(10)
)
GO
CREATE TABLE A02 (
id INT NOT NULL IDENTITY (1, 1) PRIMARY KEY(id),
name VARCHAR(10)
)
GO
CREATE TABLE A03 (
id INT NOT NULL IDENTITY (1, 1) PRIMARY KEY(id),
name VARCHAR(10)
)
GO
CREATE TABLE B01 (
id INT NOT NULL IDENTITY (1, 1) PRIMARY KEY(id),
name VARCHAR(10)
)
GO
INSERT INTO A01(NAME) VALUES
('A01'),('A01'),('A01');
GO
INSERT INTO A02(NAME) VALUES
('A02'),('A02');
GO
INSERT INTO A03(NAME) VALUES
('A03');
GO
INSERT INTO B01(NAME) VALUES
('B01');
GO
SELECT table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name LIKE 'A%';
GO
SELECT ('SELECT NAME FROM ' + table_name+';' ) SQLCMD
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name LIKE 'A%';
謝謝大大 這個也是一個高招。
如果你是用 MySQL,那就直接在 Linux console 下這串命令就行了:
<pre class="c" name="code">echo 'show tables from 資料庫名稱 like "A%"' | \
mysql -N -u 帳號 -p密碼 | \
sed 's/^.*$/select * from & where name="你要找的字串" union/;$s/ union/;/' | \
mysql -u 帳號 -p密碼