如何删除多个临时表?

时间:2015-11-25 04:49:42

标签: sql sql-server

如何从SQL Server中删除多个临时表 下面的代码给出了此错误:  信息156,第15级,状态1,第5行 关键字'drop'附近的语法不正确。

  declare @deptno int = 1
 while @deptno > (Select COUNT(*) from tbl_deptseat)+1
 Begin
   Declare @deptnamevar nvarchar(20) = '##dept'+ cast(@deptno as nvarchar(10))
    exec (drop table (@deptnamevar))
End

2 个答案:

答案 0 :(得分:0)

这似乎是接近数据处理的一种非常奇怪的方式。我不建议将此类逻辑放在表名中。相反,逻辑属于列。

但是,您想使用动态SQL:

    list_of_colors = [1, 3, 4, 4, 9, 7, 10]
    d = 5

    number_of_pairs = 0

    list_of_colors.sort() # the values in the list are not always sorted

    i = 0 
    while True:
        if i >= len(list_of_colors): 
            break
        if i != len(list_of_colors) - 1:  
            # if the number i in list and i+1 is the same or difference between them not greater than a variable d...
            if (int(list_of_colors[i]) == int(list_of_colors[i + 1])) or abs(int(list_of_colors[i]) - int(list_of_colors[i + 1])) <= d:
                #print list_of_colors[i]," ",list_of_colors[i + 1]
                number_of_pairs += 1 # increasing the number of the acceptable pairs  
                i += 2  # jump over two elements, we already counted them
                continue
        i += 1

    print number_of_pairs

答案 1 :(得分:0)

 declare @deptno int = 1

while @deptno < (Select COUNT(*) from tbl_deptseat)+1 Begin Declare @deptnamevar nvarchar(20) = '##dept'+ cast(@deptno as nvarchar(10)) Declare @dropquery nvarchar(20) = 'drop table '+ @deptnamevar exec (@dropquery) set @deptno = @deptno + 1 End