我正在编写动态查询,我需要将日期时间变量转换为时间变量
DECLARE @pdatetime_GarageOpenFrom DATETIME = '2013-07-25 08:00:00'
declare @str_SQLCount2 varchar(max)
set @str_SQLCount2 = 'select (CONVERT(CHAR(10), @pdatetime_GarageOpenFrom, 111)'
print(@str_SQLCount2)
exec(@str_SQLCount2)
答案 0 :(得分:1)
当然这会产生错误。变量@pdatetime_GarageOpenFrom
在exec语句的上下文中是未知的。
你基本上有两种选择。在sql字符串中声明变量或使用sp_executesql()
。
declare @str_SQLCount2 varchar(max)
set @str_SQLCount2 = '
DECLARE @pdatetime_GarageOpenFrom DATETIME = ''2013-07-25 08:00:00''
select CONVERT(CHAR(10), @pdatetime_GarageOpenFrom, 111)'
print(@str_SQLCount2)
exec(@str_SQLCount2)
首选方法是sp_execute_sql
,其中包含原始字符串:
DECLARE @pdatetime_GarageOpenFrom DATETIME = '2013-07-25 08:00:00'
declare @str_SQLCount2 varchar(max);
set @str_SQLCount2 = 'select CONVERT(CHAR(10), @pdatetime_GarageOpenFrom, 111)';
print(@str_SQLCount2);
exec sp_executesql @str_SQLCount2,
N'@pdatetime_GarageOpenFrom DATETIME',
@pdatetime_GarageOpenFrom = @pdatetime_GarageOpenFrom;