【问题标题】:sp_msforeachtable not available: get tablename + min(value) + max(value)sp_msforeachtable 不可用:获取表名 + min(value) + max(value)
【发布时间】:2020-02-24 11:46:21
【问题描述】:

我有一个 Azure SQL 数据库。 大多数表都有一个名为Meta_inserted(日期时间)的字段。 我想遍历所有表,如果有一个名为 Meta_insert 的字段,我想看看: 表名,min(meta_inserted) 为第一,max(meta_inserted) 为最后。

我习惯于使用 sp_msforeachtable 解决此问题,但这在 Azure SQL 中不可用。现在呢?

【问题讨论】:

  • 我想自己做(更好)sp_msforeachtable。相信网上有很多例子。
  • 您好 Henrov,如果我的回答对您有帮助,您能否将其标记为答案?这对其他社区成员可能是有益的。谢谢。
  • 对不起@LeonYue,不知怎的我错过了通知,你的回答值得称赞!谢谢!

标签: sql azure-sql-database


【解决方案1】:

sp_MSforeachtable 是 SQL Server Master 数据库中未记录的存储过程。这显然尚未移植到 Azure SQL。

所以你需要在 Azure SQL 主数据库中手动创建存储过程。

请参考:Deploy database to Azure SQL fails, sp_MSforeachtable not found

这是未记录的存储过程sp_MSforeachtable的完整代码:

USE [master]
GO
/****** Object:  StoredProcedure [sys].[sp_MSforeachtable]    Script Date: 8/18/2017 8:47:44 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

ALTER proc [sys].[sp_MSforeachtable]
    @command1 nvarchar(2000), @replacechar nchar(1) = N'?', @command2 nvarchar(2000) = null,
   @command3 nvarchar(2000) = null, @whereand nvarchar(2000) = null,
    @precommand nvarchar(2000) = null, @postcommand nvarchar(2000) = null
as
    /* This proc returns one or more rows for each table (optionally, matching 
@where), with each table defaulting to its own result set */
    /* @precommand and @postcommand may be used to force a single result set via 
a temp table. */

    /* Preprocessor won't replace within quotes so have to use str(). */
    declare @mscat nvarchar(12)
    select @mscat = ltrim(str(convert(int, 0x0002)))

    if (@precommand is not null)
        exec(@precommand)

    /* Create the select */
   exec(N'declare hCForEachTable cursor global for select ''['' + 
REPLACE(schema_name(syso.schema_id), N'']'', N'']]'') + '']'' + ''.'' + ''['' + 
REPLACE(object_name(o.id), N'']'', N'']]'') + '']'' from dbo.sysobjects o join 
sys.all_objects syso on o.id = syso.object_id '
         + N' where OBJECTPROPERTY(o.id, N''IsUserTable'') = 1 ' + N' and o.category & ' + @mscat + N' = 0 '
         + @whereand)
    declare @retval int
    select @retval = @@error
    if (@retval = 0)
        exec @retval = sys.sp_MSforeach_worker @command1, @replacechar, @command2, @command3, 0

    if (@retval = 0 and @postcommand is not null)
        exec(@postcommand)

    return @retval

参考:An introduction to sp_MSforeachtable; run commands iteratively through all tables in a database

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 2012-06-26
    • 2010-11-01
    • 2021-01-27
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2021-03-14
    相关资源
    最近更新 更多