SQL Openquery动态参数



我试图在T-SQL的Openquery函数中包含一个参数。我过去已经成功地做到了这一点,但我当前的代码不合作:

declare @bom smalldatetime
declare @eff_date smalldatetime
set @eff_date = (select min(postdate) from #temp_all)
set @bom = convert(varchar(25),dateadd(dd,-(day(@eff_date)-1),@eff_date),101)
select *
into #temp
from openquery(db,
'select l.id
   ,l.date
 from table1 l (nolock)
 inner join table2 m (nolock)
on l.id = m.id and l.date between m.start_date and m.end_date
 inner join table3 d (nolock)
on l.param = d.param
 where l.date = ''''' + convert(varchar(10),@bom,101) + '''''
 and m.param1 = ''Y''
 and m.param2 = ''N''
 and param3 is null
 and d.integer < 30
')

问题在于

 where l.date = ''''' + convert(varchar(10),@bom,101) + '''''

。有人能告诉我我做错了什么吗?

a)如果您将日期时间转换为格式120(或126),您将得到一个更好的,国际安全的ISO格式yyyy-mm-dd,永远不会被误解

b)你已经声明@bom为datetime,但然后分配一个varchar给它。如果您将其声明为varchar,则可以随后使用它来构建SQL。

c)这种事情工作(http://sqlfiddle.com/#!6/92119/4)

declare @eff_date smalldatetime
set @eff_date = dateadd(dd,-(day(getdate())-1),getdate())
declare @bom varchar(30)
set @bom = convert(varchar(20),@eff_date,120)
DECLARE @sqq NVARCHAR(300)
set @sqq =  'select 1, '''+@bom+''',3'
exec sp_executesql @sqq;

…希望你能把它应用到openquery

最新更新