0

我正在尝试执行以下代码:

use projects

set nocount on

CREATE TABLE #t (dbname VARCHAR(20),  col2 datetime)

declare @sql nvarchar(max)

declare @proc_sql nvarchar(max)

declare @table_car table (rowid int not null primary key identity(1,1), carrier varchar(500))

insert into @table_car (carrier)

select distinct t.db_name from table t with(nolock)   
              inner join table_t1  t1 with(nolock) on t.id = t1.id                          

declare @rowstoprocess int

declare @currentrow int

declare @dbname varchar(500)

set @rowstoprocess = @@rowcount

set @currentrow = 0

while @currentrow < @rowstoprocess

begin

    set @currentrow = @currentrow+1

    select @dbname = carrier
        from @table_car
        where rowid = @currentrow
         select @sql = '
        insert into #t (dbname, col2)
        SELECT DISTINCT db_name(), col_x from'+@dbname+'..table_xyz'
        set @proc_sql = replace(@sql,   @dbname, @dbname)
        exec (@proc_sql)

end 

但是,当我执行此操作时,出现错误:

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '.'.

我认为这与第 3 行无关,但在@dbnamewhile 循环内使用的变量附近有语法错误。请帮忙

4

1 回答 1

3

我相信您只是在“col_x from'+@db_name”中的 from 之后缺少一个空格。应该是这样的:

SELECT DISTINCT db_name(), col_x from '+@dbname+'..table_xyz'
-------------------------------------^

您可以做的一件事是在调试时打印出您的 sql 字符串,然后自行运行它们。更容易调试。所以在这个例子中,而不是 EXEC (@proc_sql) 执行 PRINT @proc_sql。

于 2013-09-04T19:53:19.570 回答