SQL SERVER:选择TOP 1整行进入" ROW"变量

时间:2017-06-08 08:40:55

标签: sql-server sql-server-2008 tsql

我试图将整个行作为SELECT TOP *的结果存储到一种" datarow"变量因为稍后,根据某些条件,我需要将整行插入临时表。

例如,我在下面做了。问题是,首先我必须将select top 1 *得到的值分配给变量,然后使用所有这些变量插入临时表,所以我想避免这种情况,我想插入整行的select top 1 *进入临时表,见下文。

当前情况

DECLARE @Field1 varchar(50)
DECLARE @Field2 int
DECLARE @Field3 DateTime

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

SELECT TOP 1 @Field1 = field1, @Field2 = field2, @Field3 = field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES (@Field1, @Field2, @Field3)

如果可能的话,我想做这样的事情:

所需方案

DECLARE @Row SOME_KIND_OF_DATA_ROW_VARIABLE

SET @Row = SELECT TOP 1 field1, field2, field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES @Row <-- Obviously, this is incorrect, but I would like to insert the entire row at once

3 个答案:

答案 0 :(得分:1)

如果提取行的时间并不重要(例如,您可以SELECT块内IF愉快地执行此操作),则可以使用INSERT INTO ... SELECT FROM组合用这样的东西达到预期的效果:

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

--EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
BEGIN
    INSERT INTO #tmpTbl (Field1, Field2, Field3)
    SELECT TOP 1 field1, field2, field3 from OneTable
END

答案 1 :(得分:0)

您不需要任何@Row变量。只需使用abstract class A { void X() { Y(); } abstract void Y(); } class B extends A { @Override void Y() { System.out.println("Hello from B class"); } }

即可
insert into ... select....

答案 2 :(得分:0)

你可以这样做:

Dim i as integer
Dim j as integer
Dim ws as worksheet

j = 1
i = 1
Set ws = Worksheets(j)
Do Until rs.EOF
    i = i + 1
    If i % 1000 = 0 then
        i = 1
        j = j + 1
        set ws = Worksheets(j)
    End if
    ws.range("A" & i).value = rs.Fields("SAP Code 1")
    ....
Loop

通过执行此操作,您将创建#tmpTbl,如果它已经存在,则必须在再次创建之前进行DROP。