markgrizzle
Programmer
Hi,
I need to build a list of table and column names using sysObjects and sysColumns, based on the contents of a column.
This procedure attempts to loop through each user table's varchar column(s), storing matching values in another table.
My problem is I can't figure out how to use variables for table and column names in my select statement. Can anyone see an error or suggest an alternative?
Thanks,
Mark
CREATE PROCEDURE dbo.z_detective @findstring varchar(256) as
declare @tbl varchar(50)
declare @col varchar(50)
declare @count int
drop table val
create table val
(
tablename varchar(50),
columnname varchar(50),
matches int
)
--build the cursor
declare curse cursor for
select
o.[name] as tbl, c.[name] as col
from
dbo.syscolumns c
inner join
dbo.sysobjects o on c.id = o.id
where
o.type = 'U'
and
c.xtype in (167,35)
and
c.name not in ('CreatedBy','LastEditBy')
--find potential matches
open curse
fetch next from curse into @tbl, @col
while(@@fetch_status <> -1)
begin
select @count = count(*)
from @tbl
where @col = @findstring
if @count > 0
--match found, display result
begin
insert val values(@tbl, @col, @count)
end
fetch next from curse
end
close curse
deallocate curse
select * from val order by matches desc
go
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
I need to build a list of table and column names using sysObjects and sysColumns, based on the contents of a column.
This procedure attempts to loop through each user table's varchar column(s), storing matching values in another table.
My problem is I can't figure out how to use variables for table and column names in my select statement. Can anyone see an error or suggest an alternative?
Thanks,
Mark
CREATE PROCEDURE dbo.z_detective @findstring varchar(256) as
declare @tbl varchar(50)
declare @col varchar(50)
declare @count int
drop table val
create table val
(
tablename varchar(50),
columnname varchar(50),
matches int
)
--build the cursor
declare curse cursor for
select
o.[name] as tbl, c.[name] as col
from
dbo.syscolumns c
inner join
dbo.sysobjects o on c.id = o.id
where
o.type = 'U'
and
c.xtype in (167,35)
and
c.name not in ('CreatedBy','LastEditBy')
--find potential matches
open curse
fetch next from curse into @tbl, @col
while(@@fetch_status <> -1)
begin
select @count = count(*)
from @tbl
where @col = @findstring
if @count > 0
--match found, display result
begin
insert val values(@tbl, @col, @count)
end
fetch next from curse
end
close curse
deallocate curse
select * from val order by matches desc
go
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO