如何把查询的某个表的相关字段做一个值查询出来?
有这样一个需求:
我要删除一个监测点编号如101.之前需要查询这个测点是否被其它的关系表中所使用个,如果使用则不允许删除。
表A
id 测点1 测点2 测点3 测点4 测点5 ...测点10 时间
1 103 204 101 201 104 .... 2013-8-8 10:0:0
.. ... ... .... ... .. ....
此时我根据条件查询 表A中 id=1记录符合条件(第一条),然后如何将测点1-10所有列的值是否有101的测点,如果有则不允许删除。 如果采用对应的测点如测点3有NULL的情况 怎么判断?
如何判断??? 除了一个一个列 比较的办法?
[解决办法]
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (id int,测点1 int,测点2 int,测点3 int,测点4 int,测点5 int,时间 datetime)
insert into [TB]
select 1,103,204,101,201,101,'2013-8-8 10:0:0'
select * from [TB]
SELECT CASE WHEN LEN(CONVERT(VARCHAR, 测点1) + CONVERT(VARCHAR, 测点2)
+ CONVERT(VARCHAR, 测点3) + CONVERT(VARCHAR, 测点4)
+ CONVERT(VARCHAR, 测点5)) - LEN(REPLACE(CONVERT(VARCHAR, 测点1)
+ CONVERT(VARCHAR, 测点2)
+ CONVERT(VARCHAR, 测点3)
+ CONVERT(VARCHAR, 测点4)
+ CONVERT(VARCHAR, 测点5),
'101', '')) >3 THEN
'含有多个101,禁止删除' ELSE '数据通过验证,可以删除'
end
FROM TB
--含有多个101,禁止删除
CREATE TABLE test
(
Id INT,
JD1 INT,
JD2 INT,
JD3 INT,
JD4 INT,
JD5 INT,
JD6 INT,
JD7 INT,
ModifyTime datetime
)
SELECT * FROM test
INSERT TEST
SELECT 1, 103,204,101,201,104,109,120,'2013-8-8 10:0:0' UNION ALL
SELECT 2, 103,222,121,234,121,120,120,'2013-8-8 10:0:0'
SELECT * FROM
(
SELECT id,JD,JDBH
FROM
(
SELECT ID,JD1,JD2,JD3,JD4,JD5,JD6,JD7 FROM TEST
)P
UNPIVOT
(JDBH FOR JD IN (JD1,JD2,JD3,JD4,JD5,JD6,JD7)
)AS uppvt
)a
WHERE
JDBH=103 AND ID=1
CREATE TABLE test
(
Id INT,
JD1 INT,
JD2 INT,
JD3 INT,
JD4 INT,
JD5 INT,
JD6 INT,
JD7 INT,
JD8 INT,
JD9 INT,
JD10 INT,
ModifyTime datetime
)
INSERT TEST
SELECT 1, 103,204,101,201,104,109,120,NULL,NULL,NULL,'2013-8-8 10:0:0' UNION ALL
SELECT 2, 103,222,121,234,121,120,120,NULL,NULL,NULL,'2013-8-8 10:0:0'
;WITH CTE AS
(
SELECT * FROM test A
UNPIVOT
(JDBH FOR JD IN (JD1,JD2,JD3,JD4,JD5,JD6,JD7,JD8,JD9,JD10) )AS B
)
DELETE A
FROM yourtablename A
WHERE NOT EXISTS
(
SELECT 1
FROM cte B
WHERE B.JDBH = A.JDBH
)