看似简单,但我被困在这里。我正在使用VS2010,C#环境。
所以,基本上,我们有包含表“mass”的数据库。此表包含“mass”列(值类型为double)。对于每一行,我必须找到所有记录,其中“质量”等于特定行PLUS 21中的“质量”值。并将这些结果记录放入同一数据库中的现有表中。
是否可以通过SQL完成,或者我必须使用迭代来执行此操作?
答案 0 :(得分: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
答案 1 :(得分:-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