从storedprocedure中的另一个数据库中选择数据

时间:2017-01-06 07:33:55

标签: sql-server stored-procedures

我尝试从storedprocedure中的另一个数据库的表中选择数据,另一个数据库的名称由参数给出。我收到一条错误消息:

  

'无效的对象名称[@DbName] .dbo.Setup'。

CREATE PROCEDURE [dbo].[spUndeliverableOrders]
    @DbName sysname
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @Sortfield nvarchar(50)

    SET @Sortfield = (SELECT COALESCE(Text, 'ToDoListeDatum') AS SortField FROM [@DbName].dbo.Setup WHERE label like 'ComboBoxSetupBatchReihenfolge')
END
GO

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

喜欢@ThomasSchremser说:

DECLARE @sqlquery varchar(1000)
SET @sqlquery = '(SELECT COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+@DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'')'

由您来决定使用结果填充表/变量的内容。

使用:

insert into @table(column) exec @sqlquery...

sp_executesql @sqlquery...

答案 1 :(得分:0)

您需要使用动态查询,如下所示

CREATE PROCEDURE [dbo].[spUndeliverableOrders]
        @DbName sysname
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
        DECLARE @Str varchar(max)

        CREATE TABLE #Result(Res VARCHAR(MAX))

        SET @Str = 'insert into #Result SELECT TOP 1 COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+@DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'''

        exec(@str)

        select Res from #Result
    END

答案 2 :(得分:0)

根据您的脚本修改:

    DECLARE @Str varchar(max)
    CREATE TABLE #Result(Res VARCHAR(MAX))

    SET @Str = ' SELECT TOP 1 COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+@DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'''
    insert into #Result
    EXEC(@Str)