SQL Server:将一个int列表插入临时表

时间:2011-05-06 00:06:09

标签: sql-server

我在文本文件中有一个ID列表,如下所示:

24641985 ,
24641980 ,
24641979 ,
24641978 ,
24641976 ,
24641974 ,
...
...
24641972 ,
24641971 ,
24641970 ,
24641968 ,
24641965)

有成千上万的人。

现在我需要知道这个列表中哪些ID与我表中的ID不对应。

我想我应该将它们放入临时表中,然后说出类似的内容:

select theId 
  from #tempIdCollection
 where theId not in (select customerId from customers)

问题是我不知道如何让他们进入临时表!

有人可以帮忙吗?这不一定非常有效。我只需要运行一次。任何解决方案建议都欢迎!

提前致谢!

-ev

4 个答案:

答案 0 :(得分:3)

我使用表变量。你声明它就像一个常规变量。

declare @tempThings table (items int)
insert @tempThings values (1)

答案 1 :(得分:3)

有一个“永久临时”表,也称为“收件箱”表。只是一个名为“temp_bunchOfKeys”的简单表格。

您的基本顺序是:

1)截断temp_bunchOfKeys

2)将文本文件BCP导入temp_bunchOfKeys

3)你的sql是:

select theId 
  from Temp_BunchOfKeys
 where theId not in (select customerId from customers)

答案 2 :(得分:1)

我有同样的问题但是使用字符串而不是整数,并通过使用拆分函数(请参阅下面的代码)解决它,该函数返回带有列表内容的表变量。修改功能以适合您的目的。

如何调用函数的示例

create table #t (Id int, Value varchar(64))
insert into #t (Id, Value)
select Id, Item
from dbo.fnSplit('24641978, 24641976, ... 24641972, 24641971', ',')
/*Do your own stuff*/
drop table #t

功能

if object_id(N'dbo.fnSplit', N'TF') is not null
    drop function dbo.fnSplit
GO

create function dbo.fnSplit(@string varchar(max), @delimiter char(1))
returns @temptable table (Id int, Item varchar(8000))
as
begin
    -- NB! len() does a rtrim() (ex. len('2 ') = 1)
    if ( len( @string ) < 1 or @string is null ) return

    declare @idx int
    declare @slice varchar(8000)
    declare @stringLength int
    declare @counter int ; set @counter = 1

    set @idx = charindex( @delimiter, @string )

    while @idx!= 0
    begin
        set @slice = ltrim( rtrim( left(@string, @idx - 1)))
        set @slice = replace( replace(@slice, char(10), ''), char(13), '')
        insert into @temptable(Id, Item) values(@counter, @slice)

        -- To handle trailing blanks use datalength()
        set @stringLength = datalength(@string)
        set @string = right( @string, (@stringLength - @idx) )
        set @idx = charindex( @delimiter, @string )
        set @counter = @counter + 1
    end

    -- What's left after the last delimiter
    set @slice = ltrim(rtrim(@string))
    set @slice = replace( replace(@slice, char(10), ''), char(13), '')
    insert into @temptable(Id, Item) values(@counter, @slice)

return
end
GO

答案 3 :(得分:-1)

您可以将所有这些ID从文本文件复制粘贴到Excel文件中。然后使用Sql server中的excel功能导入从该excel文件中创建一个表。真的很简单。如果您需要更具体的说明,请与我们联系。