SELECT INTO a table variable in T-SQL(SELECT INTO T-SQL 中的表变量)
问题描述
有一个复杂的 SELECT 查询,我想从中插入所有行到一个表变量中,但 T-SQL 不允许这样做.
Got a complex SELECT query, from which I would like to insert all rows into a table variable, but T-SQL doesn't allow it.
同样,您不能将表变量用于 SELECT INTO 或 INSERT EXEC 查询.http://odetocode.com/Articles/365.aspx
Along the same lines, you cannot use a table variable with SELECT INTO or INSERT EXEC queries. http://odetocode.com/Articles/365.aspx
简短示例:
declare @userData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
)
SELECT name, location
INTO @userData
FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30
表变量中的数据稍后将用于将其插入/更新回不同的表(主要是相同数据的副本,并进行少量更新).这样做的目的是让脚本比直接在正确的表中执行 SELECT INTO
更具可读性和更容易定制.性能不是问题,因为 rowcount
相当小,并且仅在需要时手动运行.
...或者只是告诉我我是否做错了.
The data in the table variable would be later used to insert/update it back into different tables (mostly copy of the same data with minor updates). The goal of this would be to simply make the script a bit more readable and more easily customisable than doing the SELECT INTO
directly into the right tables.
Performance is not an issue, as the rowcount
is fairly small and it's only manually run when needed.
...or just tell me if I'm doing it all wrong.
推荐答案
试试这样的:
DECLARE @userData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
);
INSERT INTO @userData (name, oldlocation)
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;
这篇关于SELECT INTO T-SQL 中的表变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SELECT INTO T-SQL 中的表变量


- SQL 临时表问题 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 更改自动增量起始编号? 2021-01-01