create function dbo.getname() returns varchar(50) as begin declare @tableName nchar(40) if exists(select 1 from T1 where id =1) begin set @tableName='T1' return @tableName end else if exists(select 1 from T2 where id =1) begin set @tableName='T2' return @tableName end else if exists(select 1 from T3 where id =1) begin set @tableName='T3' return @tableName end else if exists(select 1 from T4 where id =1) begin set @tableName='T4' return @tableName end else if exists(select 1 from T5 where id =1) begin set @tableName='T5' return @tableName end else if exists(select 1 from T6 where id =1) begin set @tableName='T6' return @tableName end else if exists(select 1 from T7 where id =1) begin set @tableName='T7' return @tableName end else if exists(select 1 from T8 where id =1) begin set @tableName='T8' return @tableName end else if exists(select 1 from T9 where id =1) begin set @tableName='T9' return @tableName end else if exists(select 1 from T10 where id =1) begin set @tableName='T10' return @tableName end end go
declare @tblName varchar(50),@sql varchar(1000) declare cur CURSOR FORWARD_ONLY for select name from sysobjects where xtype='u' and name like 't%' order by name --表名特征:t开头,如果有其它更详细特征可继续在where中加入open cur fetch next from cur into @tblName while @@fetch_status=0 begin select @sql=' if exsits (select * from'+@tblName+' where id=1 select '''@tblName+''' exec(@sql) fetch next from cur into @tblName end close cur deallocate cur
returns varchar(50)
as
begin
declare @tableName nchar(40)
if exists(select 1 from T1 where id =1)
begin
set @tableName='T1'
return @tableName
end
else if exists(select 1 from T2 where id =1)
begin
set @tableName='T2'
return @tableName
end
else if exists(select 1 from T3 where id =1)
begin
set @tableName='T3'
return @tableName
end
else if exists(select 1 from T4 where id =1)
begin
set @tableName='T4'
return @tableName
end
else if exists(select 1 from T5 where id =1)
begin
set @tableName='T5'
return @tableName
end
else if exists(select 1 from T6 where id =1)
begin
set @tableName='T6'
return @tableName
end
else if exists(select 1 from T7 where id =1)
begin
set @tableName='T7'
return @tableName
end
else if exists(select 1 from T8 where id =1)
begin
set @tableName='T8'
return @tableName
end
else if exists(select 1 from T9 where id =1)
begin
set @tableName='T9'
return @tableName
end
else if exists(select 1 from T10 where id =1)
begin
set @tableName='T10'
return @tableName
end
end
go
declare cur CURSOR FORWARD_ONLY for
select name from sysobjects where xtype='u' and name like 't%' order by name
--表名特征:t开头,如果有其它更详细特征可继续在where中加入open cur
fetch next from cur into @tblName
while @@fetch_status=0
begin
select @sql='
if exsits (select * from'+@tblName+' where id=1
select '''@tblName+'''
exec(@sql)
fetch next from cur into @tblName
end
close cur
deallocate cur
--在sql里直接调用该function就能得到表名了
create function dbo.getname()
returns varchar(50)--返回值varchar(50)