2011-01-12 130 views
1

我有一個表「N」列 &我必須寫一個簡單的查詢是這樣的:需要優化SQL Server查詢

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的唯一。

+2

沒有其他你正在描述的where子句的方式。 – 2011-01-12 07:01:20

+3

您可以通過編寫視圖並從中進行選擇來繞過這個問題。 – 2011-01-12 07:32:15

回答

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) 
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) 
+0

它可以在沒有遊標的情況下完成!很高興知道... – 2011-01-12 07:33:40

0

唯一的辦法我可以看到你可以寫少一點的代碼(與優化無關)不是檢查非空列。
如果它是一個謎或測試的問題,你可能會很可能使用的事實,任何+空= 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)