将选定行的SQL Store ID存储到声明的变量中。

huangapple go评论68阅读模式
英文:

SQL Store ID from selected Row to declared variable

问题

我有一个名为Cars的表,并使用以下查询语句选择满足MaxSpeed = 200条件的一行:

SELECT TOP 1 * 
FROM Cars
WHERE MaxSpeed = 200
ORDER BY [ID] DESC;

这个查询语句运行得很好,但现在我需要将这行的ID存储到一个变量中。我可以声明一个整型变量,但我不知道如何获取这行的ID。

DECLARE @id AS INT;
英文:

I have a Cars table and used this query to select a row with MaxSpeed = 200 condition:

SELECT TOP 1 * 
FROM Cars
WHERE MaxSpeed = 200
ORDER BY [ID] DESC;

This query works very well, but now I need to store this row ID to a variable. I can declare an int variable, but I don't know how can get this row ID.

DECLARE @id AS INT;

答案1

得分: 3

只需将SELECT查询的值分配给变量即可:

DECLARE @id AS INT;

SELECT TOP 1 
    @id = ID
FROM Cars
WHERE MaxSpeed = 200
ORDER BY [ID] DESC;

SELECT @id;
英文:

Just simply assign the value from the SELECT query to your variable:

DECLARE @id AS INT;

SELECT TOP 1 
    @id = ID
FROM Cars
WHERE MaxSpeed = 200
ORDER BY [ID] DESC;

SELECT @id;

huangapple
  • 本文由 发表于 2023年8月9日 12:04:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定