如何显示正确的数据库名称?

时间:2018-10-23 14:59:38

标签: sql sql-server

我想在每个数据库下运行此代码

 exec sp_MSForEachDB @command1 = 'SELECT DB_NAME() AS [CurrentDatabase], CompanyName, CASE WHEN IsCommited = 1 THEN ''Yes'' WHEN IsCommited = 0 THEN ''No'' END as CaseIsInCommit FROM  ?.dbo.CompanyCase;'

该示例的数据将为[(db1,Company1,1),(db2,Company2,1),(db3,Company3,1)]此代码假定从数据库中获取数据库名称,公司名称。表,并说明它是否已提交,但是我遇到的问题是它将显示类似的结果

该示例的数据将为[(db1,Company1,1),(db2,Company2,1),(db3,Company3,1)]

 CurrentDatabase     CampanyName     IsCommited
       db1             Company1         Yes
       db1             Company2         Yes
       db1             Company3         Yes

发生的是,对于其他公司,它总是说db1而不是db2或db3。我该如何说出正确的公司的db2和db3?看起来应该像这样

 CurrentDatabase     CampanyName     IsCommited
       db1             Company1         Yes
       db2             Company2         Yes
       db3             Company3         Yes

我认为DB_NAME()可以完成这项工作,但是它似乎卡在了同一数据库中,而其他列则移到了下一个。

2 个答案:

答案 0 :(得分:3)

我认为您需要更改数据库。试试这个:

exec sp_MSForEachDB @command1 = 'USE [?]; SELECT DB_NAME() AS [CurrentDatabase], CompanyName, CASE WHEN IsCommited = 1 THEN ''Yes'' WHEN IsCommited = 0 THEN ''No'' END as CaseIsInCommit FROM  ?.dbo.CompanyCase;'

here是一个简单的示例。

答案 1 :(得分:0)

问题是您没有更改要在哪个数据库上执行。这是使用一些动态SQL的一种方法,

    DECLARE @DBNames TABLE
    (
        ID INT IDENTITY(1,1)
        ,DBNAME nVARCHAR(200)

    )

INSERT INTO @DBNames
select distinct
 db_name(s_mf.database_id) dbName 
    from
        sys.master_files s_mf
    where
        s_mf.state = 0 and -- ONLINE
        has_dbaccess(db_name(s_mf.database_id)) = 1 -- Only look at databases to which we have access
    and db_name(s_mf.database_id) not in ('master','tempdb','model','msdb','distribution')
    and db_name(s_mf.database_id) not like 'MSDB%'
    and db_name(s_mf.database_id) not like 'Report%'
    and type=1
    order by 
        db_name(s_mf.database_id)

        DECLARE @Count INT, @Counter INT,   @CurrentName NVARCHAR(260)
    SELECT @Count = COUNT(*) FROM @DBNames m
    SET @Counter = 1

DECLARE @SQL1 as nVARCHAR (MAX)

    WHILE @Counter <= @Count
    BEGIN
        SELECT @CurrentName = DBNAME FROM @Modules m WHERE ID = @Counter
         set @SQL1 ='USE ' + @CurrentName  +';' +  'SELECT '+@CurrentName+' [CurrentDatabase], CompanyName, CASE WHEN IsCommited = 1 THEN ''Yes'' WHEN IsCommited = 0 THEN ''No'' END as CaseIsInCommit FROM  ?.dbo.CompanyCase;'
         exec @SQL1

        SET @Counter = @Counter + 1
    END