SQL获取id值并插入到另一列

发布于 2024-11-17 00:03:08 字数 671 浏览 4 评论 0原文

我正在尝试创建一个 sql 语句,该语句将插入一条初始记录、检索新的 id(自动编号主键)并将其插入到表中的另一列中以用作默认值。

这就是我到目前为止所拥有的:

INSERT INTO users (first_name, last_name, email, password, shot, year, campus, subject,

 qual_level, job_title, blurb, presentions, offers, moderated, version_current,

 version_replace, salt, loggable) VALUES (@sfirst_name, @slast_name, @semail, @spassword,

 @sshot, @syear, @scampus, @ssubject, @squal_level, @sjob_title, @sblurb, @spresentions, 

@soffers, @smoderated, @scurrent_version, @sversion_replace, @ssalt, 1) SELECT 

SCOPE_IDENTITY() as NewId UPDATE users (version_replace) VALUES (NewId) WHERE id = NewId

这不能按原样工作,我可以用手来纠正语法

I am attempting to create an sql statement that will insert an inital record, retrieve the new id (a autonumber primary key) and insert that into another column in the table to serve as a defualt value.

This is what I have so far:

INSERT INTO users (first_name, last_name, email, password, shot, year, campus, subject,

 qual_level, job_title, blurb, presentions, offers, moderated, version_current,

 version_replace, salt, loggable) VALUES (@sfirst_name, @slast_name, @semail, @spassword,

 @sshot, @syear, @scampus, @ssubject, @squal_level, @sjob_title, @sblurb, @spresentions, 

@soffers, @smoderated, @scurrent_version, @sversion_replace, @ssalt, 1) SELECT 

SCOPE_IDENTITY() as NewId UPDATE users (version_replace) VALUES (NewId) WHERE id = NewId

This isn't working as is and I could use a hand to correct the syntex

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷默言语 2024-11-24 00:03:08

您的更新不正确,应该是

UPDATE 
    users 
SET 
    version_replace =  SCOPE_IDENTITY()

WHERE id = SCOPE_IDENTITY()

这是因为此语句

SELECT SCOPE_IDENTITY() as NewId

对以下语句没有影响

如果您愿意,您还可以使用变量来存储 NewID

DECLARE @NewID  int
SET @NewId =  SCOPE_IDENTITY()

UPDATE 
    users 
SET 
   version_replace =  @NewID  
WHERE id =@NewID 

如果您是对多行执行此操作,您可能需要查看 OUTPUT 子句

Your update isn't right it should be

UPDATE 
    users 
SET 
    version_replace =  SCOPE_IDENTITY()

WHERE id = SCOPE_IDENTITY()

This is because this statement

SELECT SCOPE_IDENTITY() as NewId

Had no impact on the following statement

If you want you can also use a variable to store the NewID

DECLARE @NewID  int
SET @NewId =  SCOPE_IDENTITY()

UPDATE 
    users 
SET 
   version_replace =  @NewID  
WHERE id =@NewID 

If you were doing this with multiple rows you would probably want to look at the OUTPUT Clause

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文