SQL 选择一行并存储在 SQL 变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3773658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Select a row and store in a SQL variable
提问by EJC
So, I'm writing this Stored Proc and I really suck at SQL.
所以,我正在编写这个存储过程,我真的很擅长 SQL。
My Question to you guys is:
我对你们的问题是:
Can I select an entire row and store it in a variable?
我可以选择整行并将其存储在变量中吗?
I know I can do something like:
我知道我可以这样做:
declare @someInteger int
select @someInteger = (select someintfield from sometable where somecondition)
But can I select the entire row from sometable
and store it in a variable?
但是我可以从中选择整行sometable
并将其存储在变量中吗?
回答by Bennor McCarthy
You can select the fields into multiple variables:
您可以将字段选择为多个变量:
DECLARE @A int, @B int
SELECT
@A = Col1,
@B = Col2
FROM SomeTable
WHERE ...
Another, potentially better, approach would be to use a table variable:
另一种可能更好的方法是使用表变量:
DECLARE @T TABLE (
A int,
B int
)
INSERT INTO @T ( A, B )
SELECT
Col1,
Col2
FROM SomeTable
WHERE ...
You can then select from your table variable like a regular table.
然后,您可以像常规表一样从表变量中进行选择。
回答by brendan
You could create a table variable that matches your table schema and store the single row in it:
您可以创建一个与您的表架构匹配的表变量并将单行存储在其中:
declare @myrow table(field0 int,field1 varchar(255))
insert into @myrow
select field0,field1 from mytable where field0=1
回答by webMac
Please see/via:
请参阅/通过:
MSSQL Select statement with incremental integer column... not from a table
带有增量整数列的 MSSQL Select 语句......不是来自表
SELECT ROW_NUMBER() OVER( ORDER BY Column1, Column2 ) AS 'rownumber',*
FROM YourTable