Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Temukan nilai kolom minimum dan maksimum dari kolom umum di semua tabel dalam database SQL Server 2008

Sesuatu seperti berikut ini akan berfungsi

DECLARE @C1           AS CURSOR,
        @TABLE_SCHEMA SYSNAME,
        @TABLE_NAME   SYSNAME,
        @HasCreated   BIT,
        @HasUpdated   BIT,
        @MaxDate      DATETIME,
        @MinDate      DATETIME,
        @SQL          NVARCHAR(MAX) 

SET @C1 = CURSOR FAST_FORWARD FOR 
SELECT TABLE_SCHEMA,
       TABLE_NAME,
       COUNT(CASE
               WHEN COLUMN_NAME = 'CREATED_DATETIME' THEN 1
             END) AS HasCreated,
       COUNT(CASE
               WHEN COLUMN_NAME = 'UPDATED_DATETIME' THEN 1
             END) AS HasUpdated
FROM   INFORMATION_SCHEMA.COLUMNS
WHERE  COLUMN_NAME IN ( 'CREATED_DATETIME', 'UPDATED_DATETIME' )
GROUP  BY TABLE_SCHEMA,
          TABLE_NAME 


OPEN @C1;

FETCH NEXT FROM @C1 INTO @TABLE_SCHEMA , @TABLE_NAME , @HasCreated , @HasUpdated ;
WHILE @@FETCH_STATUS = 0
BEGIN

SET @SQL = N'
SELECT @MaxDate = MAX(D),
       @MinDate = MIN(D)
FROM   ' + QUOTENAME(@TABLE_SCHEMA) + '.' + QUOTENAME(@TABLE_NAME) + N' 
       CROSS APPLY (VALUES ' + 
                  CASE WHEN @HasCreated = 1 THEN N'(CREATED_DATETIME),' ELSE '' END + 
                  CASE WHEN @HasUpdated = 1 THEN N'(UPDATED_DATETIME),' ELSE '' END + N'
                           (@MaxDate),
                           (@MinDate)) V(D) 

'

EXEC sp_executesql 
    @SQL,
    N'@MaxDate datetime OUTPUT, @MinDate datetime OUTPUT', 
    @MaxDate = @MaxDate OUTPUT, 
    @MinDate = @MinDate OUTPUT

  FETCH NEXT FROM @C1 INTO @TABLE_SCHEMA , @TABLE_NAME , @HasCreated , @HasUpdated ;
END

SELECT @MaxDate AS [@MaxDate], @MinDate AS [@MinDate]


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Karakter yang tidak dapat dicetak dalam output bcp.exe

  2. kueri SQL; horisontal ke vertikal

  3. Kembalikan konstanta BIT dari SQL Stored Procedure

  4. SQL Server - literal boolean?

  5. Terhubung ke Database SQL Server 2012 dengan C# (Visual Studio 2012)