sql-server - 如何在 SQL Server 中使用 SEQUENCE PK 列创建临时表
问题描述
我可以使用序列创建表,但是当我尝试将序列用于临时表时,出现错误:
无效的对象名称“[序列]”
我无法使用临时表的序列添加到主键吗?如果我只是将其更改@tist
为tist
标准表,则一切正常...问题是我需要使用临时表...由于权限而不是实际表。
drop table if exists #tist
drop table if exists #t_stg
drop sequence if exists i_seq
go
create sequence i_seq start with 1 increment by 1
/* Error is this Line */
create table #tist(id int primary key default (next value for dbo.i_seq), a int, b int)
create table #t_stg(id int, a int, b int)
insert into #t_stg(a,b) values (1,2),(3,3),(4,5)
update #t_stg set id = next value for i_seq
--select * from #t_stg
insert into #tist(id,a,b)
select * from #t_stg
SELECT * FROM #tist
解决方案
在我简单地用我的序列更新 STAGING 表而不是尝试使用 SEQUENCE 创建我的 TEMP TABLE 之后,似乎得到了我想要的东西。
DROP TABLE IF exists #t
DROP TABLE IF exists #t_stg
DROP SEQUENCE IF exists dbo.t_seq
GO
DECLARE @sql NVARCHAR(max);
DECLARE @Count INT = 981518;
CREATE SEQUENCE dbo.t_seq START WITH 1 increment BY 1
SET @sql = N'ALTER SEQUENCE dbo.t_seq RESTART WITH ' + CAST(@Count AS NVARCHAR(20)) + ';';
EXEC SP_EXECUTESQL @sql;
GO
CREATE TABLE #t(id INT, a INT, b INT)
CREATE TABLE #t_stg(id INT, a INT, b INT)
INSERT INTO #t_stg(a,b) VALUES (1,2),(3,3),(4,5)
--SELECT * FROM #t_stg
UPDATE #t_stg SET id = NEXT VALUE FOR t_seq
SELECT * FROM #t_stg
--INSERT INTO #t(id,a,b)
--SELECT * FROM #t_stg
--SELECT * FROM #t
GO
推荐阅读
- lumen - Where have I to define email for UrlGenerator?
- c++ - Maintain more than 50 digits in c++
- scrapy - What is the size limit for JsonItemExporter in Scrapy?
- vb.net - OnResize sub 在 VB.net 中没有完全工作
- html - 根据 n css 选择 nth-child
- python - Python while 循环 - 这段代码实际上做了什么
- perl - 为什么 http 上传时没有创建 //Windows/Temp 临时文件?
- javascript - 为什么具有相同名称值的键的工厂函数仅在给定参数时才更改值
- javascript - 尝试使用 fetch 从浏览器通过 signedUrl 上传图像 S3,但图像在 s3 中为空白
- firebase - 如何将歌曲链接到新页面