我在我的表之一,2012年轉換INFORMATION_SCHEMA.COLUMNS COLUMN_DEFAULT到基礎數據類型
後來我想檢查的實際默認值已設置爲正確的1月1日的默認值的SMALLDATETIME列值。但是,當我讀回來自INFORMATION_SCHEMA.COLUMNS的值時,sql已添加格式。下面的代碼演示了我的問題
DECLARE
@Requireddefaultdate smalldatetime = 'Jan 1 2012',
@Actualdefaultdate smalldatetime,
@Actualdatestring nvarchar (128) ;
CREATE TABLE dbo.mytable
(thedate smalldatetime CONSTRAINT df_mytable_thedate DEFAULT
CAST('Jan 1 2012' AS smalldatetime)
) ;
INSERT INTO mytable DEFAULT VALUES;
SET @Actualdatestring = (SELECT column_default
FROM information_schema.columns
WHERE table_name = 'mytable') ;
PRINT @Actualdatestring; --result: (CONVERT([smalldatetime],'Jan 1 2012',0))
--Now I would like to convert @actualdatestring to smalldatetime
--so I can compare it to @requireddefaultdate
SET @Actualdefaultdate = @Actualdatestring; -- gives error 'Conversion failed
-- when converting character string to smalldatetime data type.'
SET @Actualdefaultdate = CAST((@Actualdatestring)AS smalldatetime);
--gives same error as above
--Added below - this is the script I used for dynamic sql
declare @dynsql nvarchar(500), @paramdef nvarchar(500);
-- SET @dynsql = N'Set @param_actdate = CAST(@param_defaultstr AS smalldatetime)';
--Above line changed as below in response to comment/answers.
--Now get single error: Incorrect syntax near '=' but seems to be closer to a correct solution.
SET @dynsql = ' ''Set '' + @param_actdate + '' = (Select '' + @param_defaultstr + '')'' ';
SET @paramdef = N'@param_actdate = @Actualdefaultdate output,
@param_defaultstr = @Actualdatestring';
EXECUTE sp_executesql @dynsql, @paramdef,
@param_actdate = @Actualdefaultdate output, @param_defaultstr = @Actualdatestring;
--finally drop the table
DROP TABLE dbo.mytable;
我也想這樣做使用sp_executesql與沒有成功(腳本上面這個加)參數轉換。
我可以做字符串操作只提取@actualdatestring的日期部分,但我覺得必須有一個更優雅的方式,我失去了一些東西明顯
感謝您的幫助
'sp_executesql'應該可以工作,你有什麼問題?您需要將字符串文字中的單引號加一。你爲什麼要檢查這個? –
謝謝。我已經接受了你的評論和Triple的回答 - 特別是關於轉義單引號並在上面編輯了我的腳本。它還沒有工作,但我認爲它更接近。原因是我的數據庫表是從一組表中自動創建的,這些表構成了數據庫需求。這種檢查默認值的算法是我的單元測試套件的一部分。謝謝你的幫助。 –
其實我可能在那裏錯誤地發送了你。 'DECLARE @DynSQL nvarchar(max)= N'SELECT @Result ='+ @Actualdatestring; DECLARE @Result smalldatetime; EXEC sp_executesql @ DynSQL,N'@ Result smalldatetime OUTPUT',@ Result OUTPUT; SELECT @ Result' –