在动态SQL查询中返回To和From日期之间的数据

时间:2018-05-23 13:37:28

标签: sql sql-server ssms-2016

此代码现在无法正常工作我尝试添加@FromDate和@ToDate参数,以便我可以选择要运行查询的日期。有任何代码校正器可以帮助吗?消息是我需要声明标量变量@FromDate和@ToDate但我已经声明了它们? “As”附近的语法显然也是错误的。

DECLARE @DatabaseName VARCHAR(100)
DECLARE @SchemaName VARCHAR(100) 
DECLARE @TableName VARCHAR(100)
DECLARE @ColumnName VARCHAR(100)
DECLARE @FullyQualifiedTableName VARCHAR(500)
DECLARE @DataType VARCHAR(50)
DECLARE @FromDate DATETIME
DECLARE @ToDate DATETIME

Declare @MySchemaName varchar(100) = 'MySystem%'

SET @FromDate = '16 May 2018'
SET @ToDate = '23 May 2018'

      ;WITH dateRange AS
(
    SELECT [Date] = DATEADD(dd, 1, DATEADD(dd, -1,@FromDate))
    WHERE DATEADD(dd, 1, @FromDate) < DATEADD(dd, 1,@ToDate)
)

    SELECT @ColumnName = COALESCE(@ColumnName, '[') + CONVERT(VARCHAR, [Date], 111) + '],['
    FROM dateRange
    OPTION (maxrecursion 0)

    SET @ColumnName = SUBSTRING(@ColumnName, 1, LEN(@ColumnName)-2)

    SELECT @ColumnName


--Create Temp Table to Save Results
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results

CREATE TABLE #Results (
    DatabaseName VARCHAR(100)
    ,SchemaName VARCHAR(100)
    ,TableName VARCHAR(100)
    ,ColumnName VARCHAR(100)
    ,ColumnDataType VARCHAR(50)
    ,StartDate Datetime2(7)
    ,EndDate Datetime2(7)
    ,TotalRowCount int
    ,NullCount int
    ,InvalidCount int
    ,ValidityCheck VARCHAR(25)




    )

    ---------------------------------------------------------DateOfBirth----------------------------------------------------------------

    DECLARE Cur CURSOR
FOR
SELECT DB_Name() AS DatabaseName
    ,s.[name] AS SchemaName
    ,t.[name] AS TableName
    ,c.[name] AS ColumnName
    ,'[' + DB_Name() + ']' + '.[' + s.name + '].' + '[' + T.NAME + ']' AS FullQualifiedTableName
    ,d.[name] AS DataType
    ,t.[create_date] AS StartDate
    ,t.[create_date] AS EndDate
FROM sys.schemas s
INNER JOIN sys.tables t ON s.schema_id = t.schema_id
INNER JOIN sys.columns c ON t.object_id = c.object_id
INNER JOIN sys.types d ON c.user_type_id = d.user_type_id
    WHERE s.name like @MySchemaName -----comment out of for all database
    and(c.name LIKE '%dob%' or c.name like '%birth%' )
    and t.create_date = @FromDate
    and t.create_date = @ToDate
   AND is_identity = 0

OPEN Cur

FETCH NEXT
FROM Cur
INTO @DatabaseName
    ,@SchemaName
    ,@TableName
    ,@ColumnName
    ,@FullyQualifiedTableName
    ,@DataType
    ,@FromDate
    ,@ToDate

WHILE @@FETCH_STATUS = 0 


BEGIN


    DECLARE @SQL VARCHAR(MAX) = NULL


    SET
     @SQL = ' Select ''' + @DatabaseName + ''' AS DatabaseName, ''' + @SchemaName + ''' AS SchemaName,
      ''' + @TableName + ''' AS TableName,
      ''' + @ColumnName + ''' AS ColumnName,
      ''' + @DataType + ''' AS DataType,


      (select  (''@FromDate'')
      As StartDate,
      (select (''@ToDate'')
      As EndDate,
      (select count(*)  from ' + @FullyQualifiedTableName + ' )
      AS TotalRowCount,
      (Select CAST(SUM(CASE WHEN ' + @ColumnName + ' IS  NULL THEN 1 ELSE 0 END) as int)  from ' + @FullyQualifiedTableName + ' )
      AS NullCount,
        (Select sum (Case when  ' + @ColumnName + ' is not null and ( ' + @ColumnName + ' <= ''1900-01-01''
     or ' + @ColumnName + '  > getdate()) then 1 else 0 end) from ' + @FullyQualifiedTableName + ' )
    AS  InvalidCount,
        (Select ''DateOfBirth'') 
        As ValidityCheck
    '


  PRINT @SQL



    INSERT INTO #Results
    EXEC (@SQL)

    FETCH NEXT
    FROM Cur
    INTO @DatabaseName
        ,@SchemaName
        ,@TableName
        ,@ColumnName
        ,@FullyQualifiedTableName
        ,@DataType
        ,@FromDate
        ,@ToDate
END



CLOSE Cur

DEALLOCATE Cur
SELECT *
FROM #Results
order by tableName desc
    --drop table #Results

2 个答案:

答案 0 :(得分:3)

当您通过import json with open('path/to/file/file_name.json', 'r') as f: my_json_obj = json.load(f) EXEC执行SQL时,范围会发生变化,并且无法再访问本地临时表和变量。

sp_executesql

为了让您的动态SQL正常工作,您必须使用正确的DECLARE @variable INT = 10 EXEC ('SELECT @variable') --Msg 137, Level 15, State 2, Line 1 --Must declare the scalar variable "@variable". 函数将您的变量值直接打印在SQL上(您必须将其写为文字)。

所以当你这样做时

CONVERT

你真的要做

'select  (''@FromDate'')'

确保它可以从字符串文字正确转换为正确的格式。

答案 1 :(得分:0)

在用于选择光标更改的where子句中

and t.create_date = @FromDate
and t.create_date = @ToDate

and t.create_date >= @FromDate
and t.create_date <= @ToDate

并在光标内部将SET @SQL = ... block更改为

SET
 @SQL = ' Select ''' + @DatabaseName + ''' AS DatabaseName, ''' + @SchemaName + ''' AS SchemaName,
  ''' + @TableName + ''' AS TableName,
  ''' + @ColumnName + ''' AS ColumnName,
  ''' + @DataType + ''' AS DataType,
  (select  ''' + convert(varchar(30),@FromDate,101) + ''') As StartDate,
  (select ''' + convert(varchar(30),@ToDate,101) + ''') As EndDate,
  (select count(*)  from ' + @FullyQualifiedTableName + ' ) AS TotalRowCount,
  (Select CAST(SUM(CASE WHEN ''' + @ColumnName + ''' IS  NULL THEN 1 ELSE 0 END) as int)  from ' + @FullyQualifiedTableName + ' )
  AS NullCount,
    (Select sum (Case when  ' + @ColumnName + ' is not null and ( ' + @ColumnName + ' <= ''1900-01-01''
 or ' + @ColumnName + '  > getdate()) then 1 else 0 end) from ' + @FullyQualifiedTableName + ' )
AS  InvalidCount,
    (Select ''DateOfBirth'') 
    As ValidityCheck
'