我有一个带'n'列的表 &安培;我必须用这种方式编写一个简单的查询:
SELECT col_1,col_2,col_3,...col_n FROM SingleTableOnly
WHERE col_1 IS NOT NULL
AND col_2 IS NOT NULL
AND col_3 IS NOT NULL
... -- for each column i need to put this condition again & again
AND col_n IS NOT NULL
请建议我更好的逻辑。
可以有类似的东西:
SELECT ALL COLUMNS FROM SingleTableOnly
WHERE ALL COLUMNS IS NOT NULL
-- i know this isnt right sql query, but trying to figure something where i can write less.
这仅适用于MS SQL Server 2005。
答案 0 :(得分:1)
如果有很多列或列数未知,您可以使用动态SQL来完成工作,但可能不是最好的方法:
declare @sql varchar(4000)
set @sql = ' where 1=1 '
declare my_cursor cursor
for
SELECT
COLUMN_NAME
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'tablename'
ORDER BY
ORDINAL_POSITION ASC;
open my_cursor
declare @colname varchar(20)
fetch next from my_cursor into @colname
while(@@FETCH_STATUS <> -1)
begin
set @sql = @sql + ' and ' + @colname + ' is not null '
fetch next from my_cursor into @colname
end
close my_cursor
deallocate my_cursor
--select 'select * from tablename ' + @sql
EXEC('select * from tablename ' + @sql)
答案 1 :(得分:0)
DECLARE @TableName VARCHAR(100)
SET @TableName = 'Your_Table_Name'
DECLARE @columns VARCHAR(MAX)
SELECT @columns = STUFF((SELECT ' and '+COLUMN_NAME +' IS NOT NULL ' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName ORDER BY ORDINAL_POSITION ASC FOR XML PATH('')),1,4,'')
EXEC('SELECT * FROM ' + @TableName ' WHERE ' + @sql)
答案 2 :(得分:0)
我能看到的唯一方法是编写少量代码(与优化无关),不检查非空列。
如果它是一个谜题或一个测试问题,你可能会使用任何事实+ null = null(请不要在实际应用中这样做),所以它会看起来
WHERE ((int_field1+int_field2+ intfield_n) IS NOT NULL)
AND ((string_field1+string_field2+...) IS NOT NULL)
AND ((datetime_field1+datetime_field2+...) IS NOT NULL)