SQL Query,列应该出现,但结果表明,它不是

时间:2017-07-13 02:29:46

标签: sql-server tsql

我很难理解为什么这个查询告诉我找不到TaxPayerID,在开始时,我显然正在检查它并且只使用数据库,它应该包含nTrucks表中的TaxPayerID列。

sp_MSforeachdb 
'
IF EXISTS (SELECT * FROM [?].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ''nTrucks'' AND COLUMN_NAME = ''TaxPayerID'')

BEGIN
    SELECT "?", nTrucks.UnitNumber, ntrucks.Companyid, nCompanyData.CompanyName, nTrucks.Owner, nTrucks.TaxPayerID
    FROM nTrucks
    INNER JOIN nCompanyData ON nTrucks.CompanyID = nCompanyData.CompanyID
    WHERE nTrucks.Owner like ''%Trucker%''
END
'

我收到多个'无效的列名'TaxPayerID'。'错误,我认为它来自不包含此列的数据库。

如果这里有人可以给我一个骨头,一个简单的“你是个假人,就这样做!”,我会非常感激。

JF

1 个答案:

答案 0 :(得分:1)

你是个假人! (你要求):))

如何调试此错误:

找到抛出错误的数据库并尝试直接在其上执行实际的SQL查询以查看它是否会编译:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ''nTrucks'' AND COLUMN_NAME = ''TaxPayerID'')

BEGIN
    SELECT nTrucks.UnitNumber, ntrucks.Companyid, nCompanyData.CompanyName, nTrucks.Owner, nTrucks.TaxPayerID
    FROM nTrucks
    INNER JOIN nCompanyData ON nTrucks.CompanyID = nCompanyData.CompanyID
    WHERE nTrucks.Owner like ''%Trucker%''
END

它会失败。

现在您知道SQL Server在查询分析时而不是运行时检查模式。 然后按照@GordonLinoff建议并将SELECT查询转换为动态SQL,如下所示:

sp_MSforeachdb 
'

IF EXISTS (SELECT * FROM [?].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ''nTrucks'' AND COLUMN_NAME = ''TaxPayerID'')

BEGIN
    EXEC( 
    ''SELECT "?", nTrucks.UnitNumber, ntrucks.Companyid, nCompanyData.CompanyName, nTrucks.Owner, nTrucks.TaxPayerID
    FROM [?]..nTrucks
    INNER JOIN [?]..nCompanyData ON nTrucks.CompanyID = nCompanyData.CompanyID
    WHERE nTrucks.Owner like ''''%Trucker%''''
    '' )
END

'

(我希望我的报价正确)

如果您的查询应该引用中央nCompareData表,则在nCompareData之前删除[?]..