SQL Server 对多列使用IS NOT NULL

but5z9lq  于 2023-02-03  发布在  其他
关注(0)|答案(5)|浏览(215)

我想检查WHERE子句中单个SQL语句中多个列的is not null约束,有没有办法做到这一点?另外,我不想在列定义上强制NOT NULL类型约束。

SELECT * FROM AB_DS_TRANSACTIONS 
WHERE FK_VIOLATION IS NULL 
AND TRANSACTION_ID NOT IN(
    SELECT distinct TRANSACTION_ID FROM AB_TRANSACTIONS) 
AND COUNTRY_ID IS NOT NULL 
AND GEO_CUST_COUNTRY_ID IS NOT NULL 
AND INVOICE_DATE IS NOT NULL 
AND ABB_GLOBALID IS NOT NULL 
AND SALES_ORG_ID IS NOT NULL 
AND DIST_ID IS NOT NULL 
AND CUSTOMER_ID IS NOT NULL 
AND REPORT_UNIT_ID IS NOT NULL 
AND CURR_INVOICE IS NOT NULL 
AND DIVISION_CODE IS NOT NULL

因此,我不想一遍又一遍地使用ISNOTNULL,而是想简化一些事情

slmsl1lt

slmsl1lt1#

您可以使用

SELECT * FROM table1 
WHERE NOT (Column1 IS NULL OR 
Column2 IS NULL OR
 Column3 IS NULL OR
 Column4 IS NULL
    IS NOT NULL)

根据OP备注,更新回答

使用INSERT和SELECT子查询插入行

INSERT INTO Table_A
    SELECT column1, column2, column3,column4 
    FROM Table_B 
    WHERE NOT (Column1 IS NULL OR 
    Column2 IS NULL OR
    Column3 IS NULL OR
    Column4 IS NULL
    IS NOT NULL);

您的查询

我可以减少大约50个字符

SELECT * FROM AB_DS_TRANSACTIONS 
WHERE 
FK_VIOLATION IS NULL 
AND TRANSACTION_ID NOT 
IN(SELECT distinct TRANSACTION_ID FROM AB_TRANSACTIONS) 
AND 
NOT (
COUNTRY_ID IS NULL  
OR GEO_CUST_COUNTRY_ID IS NULL 
OR INVOICE_DATE IS NULL 
OR ABB_GLOBALID IS NULL 
OR SALES_ORG_ID IS NULL 
OR DIST_ID IS NULL 
OR CUSTOMER_ID IS NULL 
OR REPORT_UNIT_ID IS NULL 
OR CURR_INVOICE IS NULL 
OR DIVISION_CODE IS NULL
)
qkf9rpyu

qkf9rpyu2#

SELECT * FROM AB_DS_TRANSACTIONS 
WHERE COALESCE(COUNTRY_ID,GEO_CUST_COUNTRY_ID,INVOICE_DATE,ABB_GLOBALID,SALES_ORG_ID,DIST_ID,CUSTOMER_ID,REPORT_UNIT_ID,CURR_INVOICE,DIVISION_CODE) IS NOT NULL
e3bfsja2

e3bfsja23#

我认为您正在寻找的语法是只显示所有非空的行

SELECT * from table_B
where COLUMN1 is not null and COLUMN2 is not null and COLUMN3 is not null
ljsrvy3e

ljsrvy3e4#

在BigQuery中(可以在其他数据库中使用)-我会使用concat函数。确保在需要的地方使用字符串或将字段转换为字符串。如果其中一个字段为空,Concat将返回空值。

SELECT * FROM AB_DS_TRANSACTIONS 
WHERE FK_VIOLATION IS NULL 
AND TRANSACTION_ID NOT IN(
    SELECT distinct TRANSACTION_ID FROM AB_TRANSACTIONS) 
AND concat(COUNTRY_ID,GEO_CUST_COUNTRY_ID,INVOICE_DATE,ABB_GLOBALID,SALES_ORG_ID,DIST_ID,CUSTOMER_ID,REPORT_UNIT_ID,CURR_INVOICE,DIVISION_CODE) IS NOT NULL
8oomwypt

8oomwypt5#

我认为一个策略是使用最少函数?
这里的限制是所有的参数必须是相同的类型,所以看起来OP的列可能需要转换为str或其他类型。
如果我们可以克服这个限制,我认为下面的代码应该可以检查是否有任何列为空:

SELECT  * 
FROM AB_DS_TRANSACTIONS 
WHERE FK_VIOLATION IS NULL 
AND TRANSACTION_ID NOT IN( SELECT distinct TRANSACTION_ID FROM AB_TRANSACTIONS) 
AND least(COUNTRY_ID
          ,GEO_CUST_COUNTRY_ID
          ,INVOICE_DATE
          ,ABB_GLOBALID
          ,SALES_ORG_ID
          ,DIST_ID
          ,CUSTOMER_ID
          ,REPORT_UNIT_ID
          ,CURR_INVOICE
          ,DIVISION_CODE
          ) IS NOT NULL 
;

ps -使用雪花。

相关问题