原文:
在SQL2008查找某數據庫中的列是否存在某個值
在SQL2008查找某數據庫中的列是否存在某個值
--
SQL2008查找某數據庫中的列是否存在某個值
create
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
--
使用例子,查詢庫中存在aaa這個值的列:
exec
spFind_Column_In_DB
1
,
'
aaa
'
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

