mssql怎么查询某个值存在某个表里的哪个字段的值里面?

mahuatengBC 2013-03-14 10:59:39
如题:已知表名,字段名,

要求是,从外部传一个变量值,如何查找这些字段里包含传来的变量值?

求sql语句

表结构如下图



具体要求是,比如传入一个id =3 ,要求是查出这几个字段里包含3的所有记录,求sql语句!!!!


高手快来!

...全文
274 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
mahuatengBC 2013-03-14
  • 打赏
  • 举报
回复
引用 6 楼 wufeng4552 的回复:
SQL code?123456789--一个表有限的字段可以这样select * from(select Id,'id' colname from table_nameunion allselect coat_id,'coat_id' from table_nameunion allselect shirt_id,'shirt_id' from table_name)tm……
这个我之前想过,我是这么写的
select * from 表名 where coat_id=3 or shirt_id=3 or...后面省略
水族杰纶 2013-03-14
  • 打赏
  • 举报
回复
--一个表有限的字段可以这样
select * 
from(
select Id,'id' colname from table_name
union all
select coat_id,'coat_id' from table_name
union all
select shirt_id,'shirt_id' from table_name)tmp
where id=3
發糞塗牆 2013-03-14
  • 打赏
  • 举报
回复
引用 2 楼 mahuatengBC 的回复:
存储过程么??不会改.... 没有直接sql语句的?
这是函数,就和淫荡的水锅所说的,这种操作不应该频繁使用。
mahuatengBC 2013-03-14
  • 打赏
  • 举报
回复
引用 3 楼 wufeng4552 的回复:
一般这样问题都是需求不明确 和数据库设计不合理造成 对一个频繁更新的表来说 频繁遍历代价很大
数据库自己设计的.... 有木有解决方案?
水族杰纶 2013-03-14
  • 打赏
  • 举报
回复
一般这样问题都是需求不明确 和数据库设计不合理造成 对一个频繁更新的表来说 频繁遍历代价很大
mahuatengBC 2013-03-14
  • 打赏
  • 举报
回复
存储过程么??不会改.... 没有直接sql语句的?
發糞塗牆 2013-03-14
  • 打赏
  • 举报
回复
我这个是整个库查找的,你改一下吧
alter proc spFind_Column_In_DB 
( 
    @type int,--类型:1为文字类型、2为数值类型 
    @str nvarchar(100)--需要搜索的名字 
) 
as
    --创建临时表存放结果 
    create table #tbl(PK int identity primary key ,tbl sysname,col sysname) 
    declare @tbl nvarchar(300),@col sysname,@sql nvarchar(1000) 
    if @type=1  
    begin
        declare curTable cursor fast_forward 
        for 
            select '['+SCHEMA_NAME(SCHEMA_ID)+'].['+o.name+']' tableName,'['+c.name+']' columnName from sys.columns c inner join sys.objects o on c.object_id=o.object_id 
            where o.type_desc='user_table' and user_type_id in (167,175,231,239,35,99) 
    end
    else
    begin 
        declare curTable cursor fast_forward 
        for 
        select '['+SCHEMA_NAME(SCHEMA_ID)+'].['+o.name+']' tableName,'['+c.name+']' columnName from sys.columns c inner join sys.objects o on c.object_id=o.object_id 
            where o.type_desc='user_table' and user_type_id in (56,48,52,59,60,62,106,108,122) 
    end
    open curtable 
    fetch next from curtable into @tbl,@col 
    while @@FETCH_STATUS=0 
    begin
        set @sql='if exists (select * from '+@tbl+' where '
        if @type=1 
        begin
            set @sql += @col + ' like ''%'+@str +'%'')'
        end
        else 
        begin
            set @sql +=@col + ' in ('+@str+'))'
        end
  
        set @sql += ' INSERT #TBL(tbl,col) VALUES('''+@tbl+''','''+@col+''')'
        --print @sql 
        exec (@sql) 
        fetch next from curtable into @tbl,@col 
    end
    close curtable  
    deallocate curtable 
    select * from #tbl

22,209

社区成员

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

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