sp_msforeachtable不可用:获取表名+最小值(值)+最大值(值)

问题描述 投票:0回答:1

我有一个Azure SQL数据库。大多数表都有一个名为Meta_inserted(日期时间)的字段。我想浏览所有表,如果有一个名为Meta_insert的字段,我想看看:Table_name,最小值(meta_inserted)在前,最大值(meta_inserted)在后。

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

sql azure-sql-database
1个回答
0
投票

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

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

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.