0

这似乎很容易,但我被困在这里。我正在使用 VS2010,C# 环境。

所以,基本上,我们有包含表“masses”的数据库。此表包含列“质量”(值类型为双精度)。对于每一行,我必须在特定行 PLUS 21 中找到“质量”等于“质量”值的所有记录。并将这些结果记录放入同一数据库中的现有表中。

它可以通过 SQL 完成还是我必须使用迭代来完成?

4

2 回答 2

1

您可以使用in语句来执行此操作。

INSERT INTO SomeOtherTable (<columns you want>)
SELECT <columns you want>
FROM   Masses
WHERE  Mass IN (SELECT mass + 21
                FROM   masses)

或者,这可以使用以下方式编写EXISTS

INSERT INTO SomeOtherTable (<columns you want>)
SELECT <columns you want>
FROM   Masses
WHERE  EXISTS
(
    SELECT NULL
    FROM   masses M
    WHERE  Masses.Mass = M.Mass + 21 
)

或使用派生表:

INSERT INTO SomeOtherTable (<columns you want>)
SELECT <columns you want>
FROM   Masses
       INNER JOIN (SELECT Mass + 21 AS NewMass
                   FROM   masses) AS NewMasses
         ON NewMasses.NewMass = Masses.Mass
于 2013-01-30T12:12:43.050 回答
-1

您可以使用游标遍历表。游标可以将行中列的值分配给 SQL 变量。然后对每一行进行过滤,然后对结果进行任何您想要的操作。

-- Create a cursor that iterates through the table and only reads the 'mass' column
DECLARE C1 CURSOR FOR 
SELECT mass FROM masses
DECLARE @current decimal

OPEN C1

-- Copy the value from the 'mass' column to a vaiable
FETCH NEXT FROM C1 INTO @current

WHILE @@fetch_status = 0
BEGIN

    -- Select the rows that have mass = current row mass + 21
    SELECT * -- This ca be improved by selecting only the rows you need
    FROM masses
    WHERE mass = @current + 21

    FETCH NEXT FROM C1 INTO @current
END
CLOSE C1
DEALLOCATE C1

在嵌套选择中,您可以将所有行复制到目标表,例如通过更改以下行:

INSERT INTO DESTINATION_TABLE(row1, row2, ..., rown)
SELECT (row1, row2, ..., rown)
FROM masses
WHERE mass = @current + 21
于 2013-01-30T12:20:23.847 回答