简体   繁体   English

需要优化SQL Server查询

[英]need to optimize sql server query

I have a table with 'n' columns & I have to write a simple query this way : 我有一个带有'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

Please suggest me better logic for the same. 请为我建议更好的逻辑。

Can there be something like : 可以有这样的东西:

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.

This is specific to MS SQL Server 2005 only. 这仅适用于MS SQL Server 2005。

if there are a lot of columns or the number of columns is unknown you could use dynamic sql to get the job done, probably not the best way though: 如果有很多列或列数未知,则可以使用动态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)
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)

The only way I can see you can write a little less code (which have nothing to do with optimization) is not to check non-null columns. 我所看到的唯一可以减少编写代码(与优化无关)的方法是不检查非null列。
If it's a puzzle or a test question, you might probably use the fact that anything+null = null (please, don't do it in real application), so it will look 如果是难题或测试问题,您可能会使用“ null + 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM