使用SQL Server中的cte_results插入或更新数据

时间:2018-04-10 17:01:31

标签: sql sql-server tsql

我有一个cte包含列数的查询,我想插入一条记录,如果我插入的表中不存在该查询结果中的ID,或者ID存在我想使用ID更新数据。

到目前为止,我已经尝试过这个:

WITH cte_base as(
SELECT DISTINCT ID, statusID
FROM testtable
)

SELECT *
FROM cte_base

IF EXISTS(SELECT * FROM Newtable WHERE EXISTS (SELECT ID FROM cte_base))
UPDATE newtable
SET statusID = 2
WHERE Newtable.ID = cte_base.ID

ELSE
INSERT INTO newtable(ID, statusID)
SELECT ID, statusID 
FROM cte_base
WHERE Newtable.ID <> cte_base.ID

我必须针对实时数据运行此查询,因此我想知道我的逻辑是否正确。

2 个答案:

答案 0 :(得分:1)

基于您提供的代码的基本合并示例。

class Screen
  def cls
    puts ("\n")
    puts "\a"
  end
def pause
   STDIN.gets
 end
end

class Script
  def display_instructions 
      Console_Screen.cls
      print "This script will take the user input of 10 integers and then 
      will 
      print the largest."
      print "\n\nPress enter to continue."
      Console_Screen.cls
      Console_Screen.pause
   end

  def getNumber #accepts user input
    list = Array.new
    10.times do
      Console_Screen.cls
      print "This script accepts 10 integers."
      print "\n\nPlease type an integer and press enter."
      input = STDIN.gets
      input.chop!
      list.push(input)
     end
   end

  def display_largest(number) #displays the largest integer entered by the 
    user
    Console_Screen.cls
    print "The largest integer is " + 
  end

 def runScript
    number = getNumber
    Console_Screen.cls
    display_largest(number)
 end
end

 #Main Script Logic
 Console_Screen = Screen.new
 LargestNum = Script.new
 answer = "" 
 loop do
   Console_Screen.cls
   print "Are you ready to start the script? (y/n): "
   print "\n\nWould you like instructions on how this script works? (h): "
   answer = STDIN.gets
   answer.chop!
   break if answer =~ /y|n|h/i
 end

 if answer == "h" or answer == "H"
  LargestNum.display_instructions
  print "Are you ready to start the script? (y/n): "
  answer = STDIN.gets
  answer.chop!
  end

 if answer == "n" or answer == "N"
  Console_Screen.cls
  puts "Okay, maybe another time.\n\n"
  Console_Screen.pause
 else
  loop do
    LargestNum.runScript
    print "\n\nEnter Q to quit or press any key to run the script again: "
    runAgain = STDIN.gets
    runAgain.chop!
    break if runAgain =~ /Q/i
  end
end

答案 1 :(得分:-1)

你想做什么?

EXISTS (SELECT ID FROM cte_base)

如果cte_base有任何记录,每次都是

这与

没什么不同
SELECT DISTINCT ID, statusID
FROM testtable 

如果测试表中有任何记录,那么每次都是如此