在存储过程中,使用表名做参数时怎样做查询?

clbug 2003-06-17 03:02:10
存储过程表名参数为@dbname,关键字@title;
怎么判断表@dbname中是否存在字段title=@title的记录?
如果直接用
Select * from @dbname where title=@title
会报错;如果用
exec('Select * from '+@dbname+' where title='''+@title+
'''')
好像不能用if exists exec('..')来判断执行结果?
各位老大,应该怎么做啊?
...全文
86 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
leimin 2003-06-17
  • 打赏
  • 举报
回复
--select * from sales

use pubs
go
declare @tbname sysname
declare @title varchar(100)
declare @Author varchar(20),@CreateTime datetime,@sql nvarchar(2000)

select @tbname='sales'
select @title='TC7777'
set @sql ='Select @Author=ord_num,@CreateTime=ord_date from '+@tbname+' where title_id='''+@title+''''
exec sp_executesql @sql ,N'@author varchar(20) output,@CreateTime datetime output'
,@Author output,@CreateTime output

print @author
print @CreateTime
leimin 2003-06-17
  • 打赏
  • 举报
回复
declare @dbname sysname
declare @title varchar(100)
declare @Author varchar(20),@CreateTime datetime,@sql nvarchar(2000)
set @sql ='Select @Author=Author,@CreateTime=CreateTime from '+@dbname+' where title='''+@title+''''
exec sp_executesql @sql ,N'@a varchar(20) output,@c datetime output'
,@Author output,@CreateTime output

dafu71 2003-06-17
  • 打赏
  • 举报
回复
create procedure sp_check @dbname varchar(100) ,@title varchar(100)
as

exec('Select * from '+@dbname+' where title='''+@title+'''')

if @@rowcount=0
print '没有满足条件的数据'
else
print '有'+@@rowcount+'条满足条件的数据'
clbug 2003-06-17
  • 打赏
  • 举报
回复
@@RowCount是上一次语句影响的数据行的行数,是全局变量来的;
用它来判断的话,如果数据库有多个线程在运行的时候会不会出问题啊?
friendliu 2003-06-17
  • 打赏
  • 举报
回复
表名的变量用“+”来连接赋值

对于字段可以直接赋值。
CrazyFor 2003-06-17
  • 打赏
  • 举报
回复
exec('Select * from '+@dbname+' where title=@title')
psxfghost 2003-06-17
  • 打赏
  • 举报
回复
set @rowcount=0
exec('Select * from '+@dbname+' where title='''+@title+
'''')
if (@rowcount=0)
print '没有满足条件的数据'
else
print '有'+@rowcount+'条满足条件的数据'
joygxd 2003-06-17
  • 打赏
  • 举报
回复
declare @name varchar(8000)
@name='Select * from '+@dbname +'where title= '''+@title+''''
exec @name
happydreamer 2003-06-17
  • 打赏
  • 举报
回复
create procedure sp_check @dbname varchar(100) ,@title varchar(100)
as

exec('Select * from '+@dbname+' where title='''+@title+'''')

if @@rowcount>0
begin
your sql statement
end
robin_xin_xin 2003-06-17
  • 打赏
  • 举报
回复
关注!
up

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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