-- 我想传递时间为什么不行呢,请问各位大哥怎么实现,小弟先谢了
DECLARE @str AS NVARCHAR(max);
DECLARE @ParmDefinition AS NVARCHAR(MAX)
SET @str = N'SELECT * FROM dbo.Orders WHERE RequiredDate BETWEEN ''@s'' AND ''@e''';
SET @ParmDefinition = N'@s DATETIME,@e DATETIME';
DECLARE @startdate AS nvarchar
DECLARE @enddate AS nvarchar
SET @startdate = '2008-06-1';
SET @enddate ='2008-09-31';
PRINT @str;
DECLARE @ss AS NVARCHAR(max);
set @ss = N'@s = @startdate ,@e= @enddate';
EXECUTE sp_executesql @str, @ParmDefinition, @ss;
最上面的语句没有定义 DECLARE @startdate AS nvarchar的长度,所以始终为1
补充答案时你把变量@startdate放在单引号之内是无效的
试试这个
DECLARE @str AS NVARCHAR(max);
DECLARE @ParmDefinition AS NVARCHAR(MAX)
DECLARE @startdate AS nvarchar(16)
DECLARE @enddate AS nvarchar (16)
SET @startdate = '1996-01-01';
SET @enddate ='1996-12-31';
print @startdate
SET @str = N'SELECT * FROM dbo.Orders WHERE RequiredDate BETWEEN '''+@startdate +''' AND '''+@enddate+ ''' '
print @str
EXECUTE sp_executesql @str
如果想按真正的日期比较,可以用cast
DECLARE @str AS NVARCHAR(max);
DECLARE @ParmDefinition AS NVARCHAR(MAX)
DECLARE @startdate AS nvarchar(16)
DECLARE @enddate AS nvarchar (16)
SET @startdate = '1996-01-01';
SET @enddate ='1996-12-31';
print @startdate
SET @str = N'SELECT * FROM dbo.Orders WHERE RequiredDate BETWEEN cast('''+@startdate +''' as datetime) AND cast('''+@enddate+ ''' as datetime) '
print @str
EXECUTE sp_executesql @str
或者效率更高一些,直接用日期比较
DECLARE @str AS NVARCHAR(max);
DECLARE @ParmDefinition AS NVARCHAR(MAX)
DECLARE @startdate AS datetime
DECLARE @enddate AS datetime
SET @startdate = cast('1996-01-01' as datetime)
SET @enddate =cast('1996-12-31' as datetime)
print @startdate
print @enddate
select* from dbo.Orders where RequiredDate BETWEEN @startdate and @enddate
DECLARE @str AS NVARCHAR(max);
DECLARE @ParmDefinition AS NVARCHAR(MAX)
DECLARE @startdate AS nvarchar
DECLARE @enddate AS nvarchar
SET @startdate = '2008-06-1';
SET @enddate ='2008-09-31';
SET @str = N'SELECT * FROM dbo.Orders WHERE RequiredDate BETWEEN @startdate AND '@enddate ';
EXECUTE sp_executesql @str
这样不是更省事情啊