Functions

報告配置更改

  • October 1, 2015

我創建了一個儲存過程,我在 Erin Stellato 的 Pluralsight 課程中獲得了該過程,以報告伺服器上是否有任何配置更改作為夜間作業,如下所示:

CREATEPROCEDURE dbo.usp_SysConfigReport1 
(
   @RecentDate DATETIME,
   @OlderDate DATETIME
)

AS

BEGIN;
   IF
   @RecentDate IS NULL
   OR @OlderDate IS NULL
   BEGIN;
   RAISERROR('Input parameters cannot be NULL', 16, 1);
RETURN;
END;
SELECT  
       @@SERVERNAME ServerName,
       CaptureDate,
       [O].[Name], 
       [O].[Value] AS "OlderValue", 
       [O].[ValueInUse] AS"OlderValueInUse",
       [R].[Value] AS "RecentValue", 
       [R].[ValueInUse] AS "RecentValueInUse"

   FROM [dbo].[ConfigData] O

   JOIN

       (SELECT [ConfigurationID], [Value], [ValueInUse]

       FROM [dbo].[ConfigData]

       WHERE [CaptureDate] = @RecentDate) R on [O].[ConfigurationID] = [R].[ConfigurationID]

   WHERE [O].[CaptureDate] = @OlderDate

   AND (([R].[Value] <> [O].[Value]) OR ([R].[ValueInUse] <> [O].[ValueInUse]))

END


--------
--Capture the capture dates into #temp table1
SELECT  DISTINCT
[CaptureDate]
INTO #CapturedDates
FROM [dbo].[ConfigData]
ORDER BY [CaptureDate]

   --Create temp table2
CREATE TABLE #CapturedDates2 (
        ServerName NVARCHAR(20)
       ,[CaptureDate] DATETIMEOFFSET
       ,Name NVARCHAR(1000)
       ,[OlderValue] INT
       ,[OlderValueInUse] INT
       ,[RecentValue] INT
       ,RecentValueInUse INT   
)


------Inserting into Temp2 gin=ving error message as below

DECLARE @MINCapturedDate DATETIME
DECLARE @MAXCapturedDate DATETIME

SELECT @MINCapturedDate =(SELECT CAST(MIN([CaptureDate]) AS DATETIME) FROM #CapturedDates)
SELECT @MAXCapturedDate =(SELECT CAST(MAX([CaptureDate]) AS DATETIME) FROM #CapturedDates)

INSERT INTO #CapturedDates2
EXEC SYSDBA.dbo.usp_SysConfigReport1 @MINCapturedDate ,@MAXCapturedDate

但它給了我以下錯誤資訊:

消息 257,級別 16,狀態 3,過程 usp_SysConfigReport1,第 19 行不允許從數據類型 sql_variant 到 int 的隱式轉換。使用 CONVERT 函式執行此查詢。

編輯:包括 ConfigData 的定義

CREATE TABLE [dbo].[ConfigData] 
  ( [ConfigurationID] [INT] NOT NULL, 
    [Name] [NVARCHAR](35) NOT NULL, 
    [Value] [SQL_VARIANT] NULL, 
    [ValueInUse] [SQL_VARIANT] NULL, 
    [CaptureDate] [DATETIME] NULL ) ON [PRIMARY] 

從您提供的定義中可以看出

$$ dbo $$.$$ ConfigData $$,ValueValueInUse都被定義為SQL_VARIANT數據類型。您收到的錯誤消息是:

消息 257,級別 16,狀態 3,過程 usp_SysConfigReport1,第 19 行不允許從數據類型 sql_variant 到 int 的隱式轉換。使用 CONVERT 函式執行此查詢。

所以Value和(以及、、和的派生值也是ValueInUse如此)但您想將它們用作.SQL_VARIANT``OlderValue``OlderValueInUse``RecentValue``RecentValueInUse``INT

錯誤消息是說您需要SQL_VARIANT使用該CONVERT函式將其更改為 INT。SQL_VARIANT選擇 a並將其轉換為的範例INT

SELECT CONVERT (int, Value) FROM [dbo].[ConfigData]

CONVERT數據類型(如果可能)從 更改SQL_VARIANTINT

只要確保CONVERT使用正確的數據類型,一切都應該很好。

引用自:https://dba.stackexchange.com/questions/116712