我的一个表中有一个 smalldatetime 列,默认值为 2012 年 1 月 1 日。
稍后我想检查实际的默认值是否已设置为正确的值。但是,当我从 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 的日期部分,但我觉得必须有一种更优雅的方法,而且我遗漏了一些明显的东西
谢谢你的帮助