如何在存储过程里生成where语句

李天平 李天平 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
这样的存储过程如何写

CREATE PROCEDURE sp_Forums_GetTopics
@ForumID int,
@Subject varchar(50),
@MemberName varchar(50),
@AddedDate datetime
AS

DECLARE @strwhere varchar(500)
set @strwhere='(1=1)'

if @ForumID is not null
begin
SET @strwhere=' and '+@strwhere+'ForumID = '+@ForumID
end

if @Subject is not null
begin
SET @strwhere=' and '+@strwhere+'Subject='+@Subject
end

if @MemberName is not null
begin
SET @strwhere=' and '+@strwhere+'MemberName='+@MemberName
end

if @AddedDate is not null
begin
SET @strwhere=' and '+@strwhere+'AddedDate='+@AddedDate
end

SELECT TopicID, Subject, AddedDate, TopicReplies, TopicLastReplyDate, TopicLastPostDate, MemberID, MemberName, Email, ShowEmail
FROM v_Forums_Topics WHERE @strwhere ORDER BY TopicLastPostDate Desc

GO

解析抱错:在关键字 'ORDER' 附近有语法错误。

请问那么如何根据传进来的变量,实现动态得到where语句?
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
李天平
.NET社区 62,272 成员 668,968 内容