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

李天平 2004-07-07 01:46:20
这样的存储过程如何写

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语句?
...全文
114 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xinshaw 2004-07-07
  • 打赏
  • 举报
回复
用字串类型,将SQL语句和参数连接起来,最后Exec

Create Procedure dbo.up_Query
@ID int,
@Text nvarchar(50)
begin
declare @Sql nvarchar(500)
set @Sql = 'select * from dbo.Table where ID = ''' + @ID + ''' or Text like ''%' + @Text + '%'''
Exec(@Sql)
end
go
gaoxiaospring 2004-07-07
  • 打赏
  • 举报
回复
用动态SQL可以.如上.
但用动态SQL必须对动态执行的对象有权限才行;如果不用动态SQL就不一定对表有权限,只要能执行存储过程就可以了.
CalvinDotNet 2004-07-07
  • 打赏
  • 举报
回复
用动态SQL语句
EXEC Sp_ExecuteSql @ExecSql
brightheroes 2004-07-07
  • 打赏
  • 举报
回复
SELECT TopicID, Subject, AddedDate, TopicReplies, TopicLastReplyDate, TopicLastPostDate, MemberID, MemberName, Email, ShowEmail
FROM v_Forums_Topics WHERE @strwhere ORDER BY TopicLastPostDate Desc

---->
declare @sql varchar(8000)

set @sql = 'SELECT TopicID, Subject, AddedDate, TopicReplies, TopicLastReplyDate, TopicLastPostDate, MemberID, MemberName, Email, ShowEmail'
+ @strwhere + 'ORDER BY TopicLastPostDate Desc'
exec(@sql)

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧