我已经构建了我的sql statemnet,如下所示,但是在尝试编译时遇到错误。我知道我们可以在字符串中动态构建它但是我们知道可以像这样编写语句。请寻找建议。
INSERT INTO #tmpHierarchy (
JID ,
EntryDate ,
RefundDate ,
ActionBy ,
Comments ,
CID,
nLevel
)
SELECT
JID, EntryDate, RefundDate, ActionBy, Comments, CID, nLevel
FROM
Hierarchy
WHERE 1=1
AND
IF @FromDate <> '' AND @ToDate <> ''
BEGIN
Convert(varchar,EntryDate,112)>= @FromDate AND Convert(varchar,EntryDate,112) <= @ToDate
END
IF @ActionBy <> ''
BEGIN
ActionBy=@ActionBy
END
IF @JID > 0
BEGIN
JID=@JID
END
答案 0 :(得分:0)
您实际上必须使用查询构建varchar,然后执行它:
declare @sql varchar(max)
set @sql = 'INSERT INTO #tmpHierarchy (
JID ,
EntryDate ,
RefundDate ,
ActionBy ,
Comments ,
CID,
nLevel
)
SELECT JID,EntryDate,RefundDate,ActionBy,Comments,CID,nLevel FROM Hierarchy WHERE 1=1'
IF @FromDate <> '' AND @ToDate <> ''
BEGIN
@sql = @sql + ' and Convert(varchar,EntryDate,112)>= @FromDate AND Convert(varchar,EntryDate,112) <= @ToDate'
END
IF @ActionBy <> ''
BEGIN
@sql = @sql + ' and ActionBy=@ActionBy'
END
IF @JID > 0
BEGIN
@sql = @sql + ' and JID=@JID'
END
exec (@sql)
答案 1 :(得分:0)
您可以执行以下操作,将IF
语句合并到WHERE
子句中
SELECT JID, EntryDate, RefundDate, ActionBy, Comments, CID, nLevel
FROM Hierarchy
WHERE 1 = 1
AND (@FromDate = '' OR @ToDate = '' OR (Convert(varchar, EntryDate, 112) >= @FromDate AND Convert(varchar, EntryDate, 112) <= @ToDate))
AND (@ActionBy = '' OR ActionBy = @ActionBy)
AND (@JID <= 0 OR JID = @JID)