英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论