Pergunta

I am trying to include a parameter in T-SQL's Openquery function. I have done this successfully in the past, but my current code is not cooperating:

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
')

The issue is with the

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

line. Can someone please tell me what I am doing incorrectly?

Foi útil?

Solução

a) if you convert the datetime with format 120 (or 126) you'll get a better, internationally safe ISO format yyyy-mm-dd which can never be misinterpreted

b) You have declared @bom as datetime, but then assign a varchar to it. If you declare it as varchar instead, it can then be used to build the SQL afterwards.

c) This kind of thing works ( 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;

... hopefully you'll be apply that to your openquery

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top