截断温度 table 与删除温度 table Sql 服务器
Truncate temp table Vs Drop temp table Sql Server
有两种方法可以检查 temp table
是否存在并重新创建它
1.
IF Object_id('TEMPDB..#temp') IS NOT NULL
TRUNCATE TABLE #temp
ELSE
CREATE TABLE #temp
(
id INT
)
2.
IF Object_id('TEMPDB..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
id INT
)
使用一个比另一个有什么优势
如果有 table 调用 temp
TRUNCATE
否则创建新的 table.
IF Object_id('temp') IS NOT NULL
TRUNCATE TABLE temp
ELSE
CREATE TABLE temp
(
id INT
);
原始 table 的架构可能与 ELSE
语句中的架构不同,您将以错误的结构结束。
CREATE TABLE temp(col VARCHAR(100));
INSERT INTO temp VALUES ('a');
IF Object_id('temp') IS NOT NULL
TRUNCATE TABLE temp
ELSE
CREATE TABLE temp
(
id INT
);
INSERT INTO temp VALUES (1);
输出:
╔═════╗
║ col ║
╠═════╣
║ 1 ║
╚═════╝
如果有 table 叫作 temp
就放弃吧。然后重新创建它。
IF Object_id('TEMPDB..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
id INT
);
在此示例中,您始终可以确保获得在 CREATE
语句中定义的结构。
CREATE TABLE temp(col VARCHAR(100));
INSERT INTO temp VALUES ('a');
IF Object_id('temp') IS NOT NULL
DROP TABLE temp
CREATE TABLE temp
(
id INT
)
INSERT INTO temp
VALUES (1);
输出:
╔════╗
║ id ║
╠════╣
║ 1 ║
╚════╝
如果table不存在两种方法return相同的结构:
有两种方法可以检查 temp table
是否存在并重新创建它
1.
IF Object_id('TEMPDB..#temp') IS NOT NULL
TRUNCATE TABLE #temp
ELSE
CREATE TABLE #temp
(
id INT
)
2.
IF Object_id('TEMPDB..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
id INT
)
使用一个比另一个有什么优势
如果有 table 调用 temp
TRUNCATE
否则创建新的 table.
IF Object_id('temp') IS NOT NULL
TRUNCATE TABLE temp
ELSE
CREATE TABLE temp
(
id INT
);
原始 table 的架构可能与 ELSE
语句中的架构不同,您将以错误的结构结束。
CREATE TABLE temp(col VARCHAR(100));
INSERT INTO temp VALUES ('a');
IF Object_id('temp') IS NOT NULL
TRUNCATE TABLE temp
ELSE
CREATE TABLE temp
(
id INT
);
INSERT INTO temp VALUES (1);
输出:
╔═════╗
║ col ║
╠═════╣
║ 1 ║
╚═════╝
如果有 table 叫作 temp
就放弃吧。然后重新创建它。
IF Object_id('TEMPDB..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
id INT
);
在此示例中,您始终可以确保获得在 CREATE
语句中定义的结构。
CREATE TABLE temp(col VARCHAR(100));
INSERT INTO temp VALUES ('a');
IF Object_id('temp') IS NOT NULL
DROP TABLE temp
CREATE TABLE temp
(
id INT
)
INSERT INTO temp
VALUES (1);
输出:
╔════╗
║ id ║
╠════╣
║ 1 ║
╚════╝
如果table不存在两种方法return相同的结构: