简体   繁体   中英

How to do an IF EXISTS in hana SQL query

I have this query code:

IF EXISTS  ( 

SELECT 

 *

 FROM sys.objects

 WHERE object_id =
 OBJECT_ID(N'[dbo].[BAL_WMS_STAGING]') 

 AND type in (N'U')

)

 DROP TABLE
 [dbo].[BAL_WMS_STAGING] 

GO 
 CREATE TABLE

I am trying to use this statement to query an SAP Hana Database. The beginning of the query IF EXISTS keeps throwing an error, I assume that this means that this keyword does not exist in Hana SQL syntax. Does anyone know how to do an IF EXISTS check in Hana, as I am unable to find any answer online.

If EXISTS is a non-standard syntax that HANA doesn't support. As an alternative you can query the catalog and write a IF...THEN statement in SQLScript.

An alternative to using IF EXISTS could be something like this:

SELECT *
FROM sys.objects
WHERE object_id = (
    CASE
    WHEN EXISTS (
        SELECT object_id
        FROM sys.objects
        WHERE object_id = OBJECT_ID(N'[dbo].[BAL_WMS_STAGING]')
        AND type IN (N'U'))
    THEN (
        SELECT object_id
        FROM sys.objects
        WHERE object_id = OBJECT_ID(N'[dbo].[BAL_WMS_STAGING]')
        AND type IN (N'U'))
    ELSE
        NULL
    END
)
AND type IN (N'U')

SQLScript does not have IF EXIST condition. But same logic can be achieved by creating a variable (flag) that is initialized by your first query. You dont need to select all the columns. You can select as an example object_id.

flag = '';

SELECT object_id INTO flag FROM sys.objects
 WHERE object_id =
 OBJECT_ID(N'[dbo].[BAL_WMS_STAGING]') 
 AND type in (N'U');

IF flag != '' THEN
  DROP TABLE [dbo].[BAL_WMS_STAGING]
END IF;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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