忽略NULL值列

时间:2014-07-17 08:51:15

标签: sql sql-server sql-server-2008 tsql

我的查询看起来像这样:

select 
tbl1a.col_id as col_id_1, tbl1a.prj_name as col_name_1,
tbl1b.col_id as col_id_2, tbl1b.prj_name as col_name_2,
tbl1c.col_id as col_id_3, tbl1c.prj_name as col_name_3
from [table1] tbl1a
left join [table1] tbl1b on tbl1a.col_id = tbl1b.col_pid
left join [table1] tbl1c on tbl1b.col_id = tbl1c.col_pid

这将返回许多行,范围从

row 1
col_id_1 = col id 1 here
col_name_1 = col name 1 here
col_id_2 = col id 2 here
col_name_2 = col name 2 here
col_id_3 = col id 3 here
col_name_3 = col name 3 here

row 2
col_id_1 = col id 1 here
col_name_1 = col name 1 here
col_id_2 = col id 2 here
col_name_2 = col name 2 here
col_id_3 = null
col_name 3 = null

row 3
col_id_1 = col id 1 here
col_name_1 = col name 1 here
col_id_2 = null
col_name_2 = null
col_id_3 = null
col_name_3 = null

等等。

我知道如何将这些信息放入已定义的表格中,但不知道如何以下列形式执行此操作。对于所有行,在本例中,行1,2,3,我想定义一个临时表:

declare @temp_tbl table (full_path varchar(255), path_id int)
insert into @temp_tbl (full_path, path_id)
select (something)

@temp_tbl最终应包含以下内容:

row 1
full_path = col name 1 here\col name 2 here\col name 3 here\
path_id = col id 3 here

row 2
full_path = col name 1 here\col name 2 here\
path_id = col id 2 here

row 3
full_path = col name 1 here\
path_id = col id 1 here

是否可以在不使用循环的情况下执行此操作?或者这是一个适合的循环?

1 个答案:

答案 0 :(得分:1)

结束选择应该可以得到你想要的结果。我创建了一个表变量来模拟你的“table1”。也许不是最好的方法,但这会得到你要求的结果:)

declare @table table (
                        col_id_1 INT,
                        col_name_1 VARCHAR(30),
                        col_id_2 INT,
                        col_name_2 VARCHAR(30),
                        col_id_3 INT,
                        col_name_3 VARCHAR(30))
insert into @table (col_id_1, 
                    col_name_1, 
                    col_id_2, 
                    col_name_2, 
                    col_id_3, 
                    col_name_3)
values  (1, 'c1 name', 2, 'c2 name', 3, 'c3 name'),
        (1, 'c1 name', 2, 'c2 name', null, null),
        (1, 'c1 name', null, null, null, null)


DECLARE @temp_tbl TABLE (full_path VARCHAR(255), path_id INT)
INSERT INTO @temp_tbl (full_path, path_id)
SELECT (col_name_1 + '/' + col_name_2 + '/' + col_name_3 + '/'), col_id_3
FROM @TABLE WHERE col_id_3 IS NOT NULL
UNION
SELECT (col_name_1 + '/' + col_name_2 + '/'), col_id_2
FROM @TABLE WHERE col_id_2 IS NOT NULL AND col_id_3 IS NULL
UNION
SELECT col_name_1 + '/', col_id_1
FROM @TABLE WHERE col_id_2 IS NULL AND col_id_3 IS NULL

SELECT *
FROM @temp_tbl
ORDER BY path_id DESC