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 中的表变量
基础教程推荐
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
