"""Offline SQLite lab for SQL Chapter 24: SELECT INTO and CREATE TABLE AS SELECT."""
import json
import sqlite3
import sys
def make_case(name: str, summary: str, expected, actual) -> dict:
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main() -> None:
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.executescript(
"""
CREATE TABLE employees (
EmployeeID INT,
FirstName TEXT,
LastName TEXT,
Age INT,
Department TEXT
);
INSERT INTO employees VALUES
(1, 'John', 'Doe', 30, 'Sales'),
(2, 'Jane', 'Smith', 25, 'HR'),
(3, 'Sam', 'Brown', 28, 'IT');
"""
)
# 1. Full copy via CREATE TABLE ... AS SELECT (portable alternative in SQLite/MySQL/PostgreSQL)
cur.execute("CREATE TABLE employees_backup_all AS SELECT * FROM employees;")
all_cols = [r[1] for r in cur.execute("PRAGMA table_info(employees_backup_all)").fetchall()]
all_rows = [list(r) for r in cur.execute("SELECT * FROM employees_backup_all ORDER BY EmployeeID").fetchall()]
case1 = make_case(
"ctas_full_backup",
"Verify CREATE TABLE ... AS SELECT copies schema columns and all 3 rows into a new backup table",
{
"columns": ["EmployeeID", "FirstName", "LastName", "Age", "Department"],
"row_count": 3,
"rows": [
[1, "John", "Doe", 30, "Sales"],
[2, "Jane", "Smith", 25, "HR"],
[3, "Sam", "Brown", 28, "IT"],
],
},
{
"columns": all_cols,
"row_count": len(all_rows),
"rows": all_rows,
},
)
# 2. Filtered copy with WHERE Age > 25
cur.execute(
"""
CREATE TABLE employees_backup AS
SELECT EmployeeID, FirstName, LastName, Age, Department
FROM employees
WHERE Age > 25;
"""
)
filtered_rows = [
list(r)
for r in cur.execute("SELECT * FROM employees_backup ORDER BY EmployeeID").fetchall()
]
case2 = make_case(
"ctas_filtered_backup",
"Verify filtered CREATE TABLE ... AS SELECT copies only employees with Age > 25",
[
[1, "John", "Doe", 30, "Sales"],
[3, "Sam", "Brown", 28, "IT"],
],
filtered_rows,
)
# 3. Existing target table fails on CREATE TABLE AS, succeeds via INSERT INTO ... SELECT
dup_error = ""
try:
cur.execute("CREATE TABLE employees_backup AS SELECT * FROM employees;")
except sqlite3.OperationalError as exc:
dup_error = str(exc)
cur.execute(
"""
INSERT INTO employees_backup (EmployeeID, FirstName, LastName, Age, Department)
SELECT EmployeeID, FirstName, LastName, Age, Department
FROM employees
WHERE Age <= 25;
"""
)
merged_count = cur.execute("SELECT COUNT(*) FROM employees_backup").fetchone()[0]
case3 = make_case(
"existing_target_table_error_and_fallback",
"Verify recreating existing backup table raises OperationalError while INSERT INTO ... SELECT appends rows",
{
"already_exists_error": True,
"count_after_insert_select": 3,
},
{
"already_exists_error": "already exists" in dup_error,
"count_after_insert_select": merged_count,
},
)
# 4. Dialect probe: SQL Server SELECT INTO syntax rejected by SQLite parser
tsql_error = ""
try:
cur.execute("SELECT * INTO employees_tsql FROM employees;")
except sqlite3.OperationalError as exc:
tsql_error = str(exc)
case4 = make_case(
"select_into_dialect_probe",
"Verify SQLite rejects SQL Server SELECT ... INTO syntax, confirming CTAS portability",
True,
"syntax error" in tsql_error.lower(),
)
conn.close()
payload = {
"version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version}",
"cases": [case1, case2, case3, case4],
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。
入口文件:projects/sql-select-into-lab/explore-select-into.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-select-into.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1577.zip