SQL选择一行并将其存储在SQL变量中

时间:2022-12-30 15:43:03

So, I'm writing this Stored Proc and I really suck at SQL.

因此,我正在编写这个存储的Proc,而且我非常讨厌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?

但是我可以从某个表中选择整个行并将其存储在一个变量中吗?

3 个解决方案

#1


26  

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.

然后,您可以像常规表一样从表变量中选择。

#2


5  

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

#3


0  

Please see/via:

请参见/通过:

MSSQL Select statement with incremental integer column... not from a table

MSSQL选择语句带有递增整数列…不是从一个表

SELECT ROW_NUMBER() OVER( ORDER BY Column1, Column2 ) AS 'rownumber',*
FROM YourTable

#1


26  

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.

然后,您可以像常规表一样从表变量中选择。

#2


5  

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

#3


0  

Please see/via:

请参见/通过:

MSSQL Select statement with incremental integer column... not from a table

MSSQL选择语句带有递增整数列…不是从一个表

SELECT ROW_NUMBER() OVER( ORDER BY Column1, Column2 ) AS 'rownumber',*
FROM YourTable