为什么动态SQL不起作用?
C#中的代码:
this.DataAccess.AddParametr("@where","WHERE ta.IdMoinRef in(112,113,115)");
sqlServer中的代码:
ALTER Procedure [dbo].[sp_tblAsnad_SelectAllForReport]
@where nvarchar(max)
As
Begin
Select
ta.IdMoinRef,
ta.IdTafzeliRef,
ta.ShHesab,
ta.Bd,
ta.Bs,
ta.ShSnd,
ta.AtfSnd,
ta.DateSnd,
mo.Hmoin,
co.Hcol,
gr.Hgroup,
co.IdGroupRef,
mo.IdColRef
From tblAsnad as ta
inner join tblMoin as mo on ta.IdMoinRef=mo.IdMoin
inner join tblCol as co on mo.IdColRef=co.IdCol
inner join tblGroup as gr on co.IdGroupRef=gr.IdGroup
exec(@where)
End
答案 0 :(得分:4)
DECLARE @sql VARCHAR(1000)
SET @sql = "SELECT ... " + @where -- Your full query.
exec(@sql)
答案 1 :(得分:3)
您尝试仅执行where子句。对于动态SQL语句,必须将整个语句构建为字符串:
@s = "select * from T " + @where_clause
exec(@s)
答案 2 :(得分:2)
您需要将整个查询作为一个字符串执行,而不仅仅是WHERE子句。
答案 3 :(得分:-1)
您的代码将WHERE字符串作为字符串参数传递。那么你的proc将执行的将是:
ALTER Procedure [dbo].[sp_tblAsnad_SelectAllForReport]
@where nvarchar(max)
As
Begin
Select
ta.IdMoinRef,
ta.IdTafzeliRef,
ta.ShHesab,
ta.Bd,
ta.Bs,
ta.ShSnd,
ta.AtfSnd,
ta.DateSnd,
mo.Hmoin,
co.Hcol,
gr.Hgroup,
co.IdGroupRef,
mo.IdColRef
From tblAsnad as ta
inner join tblMoin as mo on ta.IdMoinRef=mo.IdMoin
inner join tblCol as co on mo.IdColRef=co.IdCol
inner join tblGroup as gr on co.IdGroupRef=gr.IdGroup
exec('WHERE ta.IdMoinRef in(112,113,115)')
End
哪个,显然是错的。您的整个命令需要在此处的命令文本中。