动态SQL语句和动态插入表

xcz1943 2005-09-03 10:23:05
存储过程如下,
CREATE PROCEDURE Book_PageGetBooks1
(
@ClassIDs varchar(500)
)
as
set nocount on
begin
declare @indextable table(id int identity(1,1),nid int)
insert into @indextable(nid) select Bookid from Book_Books
exec('select O.BookID from Book_Books O,@indextable t where O.BookID=t.nid and BookID in (' +@ClassIDS +') order by t.id')
end
set nocount off
GO
提示的错误是"必须声明变量 '@indextable'."
因为@ClassIDS是动态生成的字符串,所以必须要用Exec执行,但是我上面很明显的是插入了表@indextable的,但是我在insert into 前面加入exec的话,它也会提示错误
...全文
246 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
vivianfdlpw 2005-09-03
  • 打赏
  • 举报
回复
第一个方法写的时候意外删掉了一行,原来的一句:
insert into @indextable(nid) select Bookid from Book_Books
丢失了
topdogXP 2005-09-03
  • 打赏
  • 举报
回复
to xcz1943(小钊)
vivianfdlpw()的第一个方法的@indextable t表为空!当然没有结果!
vivianfdlpw 2005-09-03
  • 打赏
  • 举报
回复
比如你有一个bookid为2,那么当@ClassIDS为2的时候可以得到一条记录。但是当@ClassIDS为12,22,32....等包括数字2的值的时候也可以得到纪录。所以两边要加分隔符来区分
xcz1943 2005-09-03
  • 打赏
  • 举报
回复
EXEC Book_PageGetBooks1 @ClassIDS="2,62,26,11,9,110,83,87,113"
我是这样执行存储过程的,应该算是用分隔符了吧
我刚刚也查询了一下charindex的用法,感觉我会被一些逗号搞晕掉
sql里面的符号感觉特别麻烦
vivianfdlpw 2005-09-03
  • 打赏
  • 举报
回复
","是ID之间的分隔符,你要用你的@ClassIDS得分隔符替换
xcz1943 2005-09-03
  • 打赏
  • 举报
回复
to: vivianfdlpw
你的charindex(','+convert(varchar,BookID)+',',','+@ClassIDS +',')>0
得不到任何结果
上面的那个函数可以代替BookID in ('+@ClassIDs+')吗
vivianfdlpw 2005-09-03
  • 打赏
  • 举报
回复
或者

CREATE PROCEDURE Book_PageGetBooks1
(
@ClassIDs varchar(500)
)
as
set nocount on
begin
create table #(id int identity(1,1),nid int)
insert into # select Bookid from Book_Books

--查询
exec(' select O.BookID'+
' from Book_Books O,'+
' # t '+
' where O.BookID=t.nid'+
' and BookID in ('+@ClassIDS +')'+
' order by t.id'
)

drop table #
end
set nocount off
GO
vivianfdlpw 2005-09-03
  • 打赏
  • 举报
回复
CREATE PROCEDURE Book_PageGetBooks1
(
@ClassIDs varchar(500)
)
as
set nocount on
begin
declare @indextable table(id int identity(1,1),nid int)

--查询
select O.BookID
from Book_Books O,
@indextable t
where O.BookID=t.nid
and charindex(','+convert(varchar,BookID)+',',','+@ClassIDS +',')>0
order by t.id
end
set nocount off
GO
iwl 2005-09-03
  • 打赏
  • 举报
回复
vivianfdlpw() 每次都那么早

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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