sp_msforeachtable没有给我正确的结果

时间:2010-06-30 14:21:30

标签: tsql sql-server-2005 sp-msforeachtable

我想使用sp_msforeachtable为数据库中的某些表做一些工作。我使用 IF 语句来过滤表格。但它没有给我正确的答案。如下面的脚本所示,我使用 AdventureWorks 进行测试。我想在每个表上做一些工作,除了 Person.Address Person.Contact Person.CountryRegion 。如您所见,这些表仍包含在结果中。为什么?谁能帮我解决问题?非常感谢。

sp_msforeachtable '
IF ''?'' <> ''Person.Address'' AND ''?'' <> ''Person.Contact'' AND ''?'' <> ''Person.CountryRegion''
BEGIN
    PRINT ''?''
END
';

结果是:

[Sales].[Store]
[Production].[ProductPhoto]
[Production].[ProductProductPhoto]
[Sales].[StoreContact]
[Person].[Address] <------------------------------
[Production].[ProductReview]
[Production].[TransactionHistory]
[Person].[AddressType]
[Production].[ProductSubcategory]
[dbo].[AWBuildVersion]
[Production].[TransactionHistoryArchive]
[Purchasing].[ProductVendor]
[Production].[BillOfMaterials]
[Production].[UnitMeasure]
[Purchasing].[Vendor]
[Purchasing].[PurchaseOrderDetail]
[Person].[Contact] <------------------------------
[Purchasing].[VendorAddress]
[Purchasing].[VendorContact]
[Purchasing].[PurchaseOrderHeader]
[Sales].[ContactCreditCard]
[Production].[WorkOrder]
[Person].[ContactType]
[Sales].[CountryRegionCurrency]
[Production].[WorkOrderRouting]
[Person].[CountryRegion] <------------------------------
[Sales].[CreditCard]
[Production].[Culture]
[Sales].[Currency]
[Sales].[SalesOrderDetail]
[Sales].[CurrencyRate]
[Sales].[Customer]
[Sales].[SalesOrderHeader]
[Sales].[CustomerAddress]
[HumanResources].[Department]
[Production].[Document]
[HumanResources].[Employee]
[Sales].[SalesOrderHeaderSalesReason]
[Sales].[SalesPerson]
[HumanResources].[EmployeeAddress]
[HumanResources].[EmployeeDepartmentHistory]
[HumanResources].[EmployeePayHistory]
[Sales].[SalesPersonQuotaHistory]
[Production].[Illustration]
[Sales].[SalesReason]
[Sales].[Individual]
[Sales].[SalesTaxRate]
[HumanResources].[JobCandidate]
[Production].[Location]
[Sales].[SalesTerritory]
[Production].[Product]
[Sales].[SalesTerritoryHistory]
[Production].[ScrapReason]
[HumanResources].[Shift]
[Production].[ProductCategory]
[Purchasing].[ShipMethod]
[Production].[ProductCostHistory]
[Production].[ProductDescription]
[Sales].[ShoppingCartItem]
[Production].[ProductDocument]
[Production].[ProductInventory]
[Sales].[SpecialOffer]
[Production].[ProductListPriceHistory]
[Sales].[SpecialOfferProduct]
[Production].[ProductModel]
[Person].[StateProvince]
[Production].[ProductModelIllustration]
[dbo].[DatabaseLog]
[Production].[ProductModelProductDescriptionCulture]
[dbo].[ErrorLog]

2 个答案:

答案 0 :(得分:3)

您是否尝试过添加括号?

sp_msforeachtable '
IF ''?'' <> ''[Person].[Address]'' AND ''?'' <> ''[Person].[Contact]'' AND ''?'' <> ''[Person].[CountryRegion]''
BEGIN
    PRINT ''?''
END
';

答案 1 :(得分:3)

为什么不直接使用系统表,因为您希望所有表都不在Person模式中?

    select sys.schemas.name + '.' + sys.tables.name from sys.tables 
    inner join sys.schemas on sys.tables.schema_id = sys.schemas.schema_id 
    where sys.schemas.name <> 'Person'
相关问题