create table from if statement SQL - sql

I have this code in my SQL, however the if statement seems to be not working at all. Every time I run the query below.. I always have an error that says...
Msg 2714, Level 16, State 1, Line 39
There is already an object named '##TEMP1' in the database.
QUERY BELOW...
IF (SELECT COUNT (*) FROM ##TEMP1 WHERE [ACTION] NOT LIKE 'ok' ) >=1
BEGIN
SELECT * INTO ##newtable FROM ##TEMP1 ORDER BY 1 ASC
Select ' ' = 'MESSAGE'
SELECT * FROM ##newtable
END
ELSE
BEGIN
Select [MESSAGE] = 'MESSAGE' INTO ##newtable
SELECT * FROM ##newtable
END
is there any way that the query creates a final table '##temp1' given that the condition is met? So it's either the first begin statement or the second one.
Thank you.

Related

Automation Anywhere SQL results

I am trying to capture if my SQL Query have 0 rows or multiple rows. If it has 0 rows then I will insert, if 1 will perform an update, if > 1 will perform additional analysis.
Is there a way I can see if my query resulted in x results or no results in automation anywhere?
Any assistance will be appreciated.
You can make use of if exists and if not exists and check if rows exists or not, or even if there are multiple before doing the insert.
Here is a simple example using if not exists where if the row doesn't exist on dbo.Table it will insert a row. If it already exists then the ID will be logged to an Error table.
declare #InsertID int = 5, #Name nvarchar(max) = 'some name'
if ((select count(1) from dbo.Table where ID = #InsertID) > 1) -- detect error; more than one record for an id
begin
insert into dbo.Error (ErrorID, ErrorDate)
select #InsertID, getdate()
end
else if not exists (select 1 from dbo.Table where ID = #InsertID) -- no record exists for ID, insert it
begin
insert into dbo.Table (ID, Name)
select #InsertID, #Name
else if exists (select 1 from dbo.Table where ID = #InsertID) -- update the single record
begin
update dbo.Table set Name = #Name where ID = #InsertID
end
A2019 returns the results of a SQL Query as a table...
You could have an if statement right after your query which checks to see if the row count of the returned table is > 0 then take action accordingly.

Error while declaring a new variable

I need to create a new variable (average of AGE) that I would like to get from another table named:source_table.
I wrote the following lines but got an error:
DECLARE #mean_AGE decimal;
set #mean_AGE = select AVG( AGE ) from source_table;
Error details:
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'select'.
How can I solve this issue?
An update:
I used this code based on the answers below but still an error.
DECLARE #mean_AGE decimal;
select #mean_AGE = AVG(AGE) from source_table;
--DELETE temp_table
SELECT TOP 1000
[AGE]=iif(AGE='NA',#mean_AGE,AGE)
INTO temp_table
FROM [source_table]
But got this error:
Must declare the scalar variable "#mean_AGE".
Try this instead, use a select. set #mean_AGE = (select AVG( AGE ) from source_table)
Change the query to:
select #mean_AGE = AVG(AGE) from source_table;
Updates
Remove those semi-colons
DECLARE #mean_AGE decimal
select #mean_AGE = AVG(AGE) from source_table
; denotes end of batch script so a statement after that is effectively new batch script.
Secondly,
This one will not work because the data type in iif true and false condition must match.
SELECT TOP 1000
[AGE]=iif(AGE='NA',#mean_AGE,AGE)
INTO temp_table
FROM [source_table]
Change to:
SELECT TOP 1000
[AGE]=iif(AGE=0,#mean_AGE,AGE)
INTO temp_table
FROM [source_table]

SQL Server - Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. ErrorCode HY000

I'm trying to execute the query bellow on a SQL server database
but it throws the following error:
Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS.
Code:
IF #status = 1
BEGIN
..... -- execute something
END
ELSE
BEGIN
select top #URL.nof# *
from lead_feed
where
lead_tstamp > '2017-09-01'
and egoiID is not null
and rtrim(ltrim(lead_name)) <> ''
and rtrim(ltrim(lead_surname)) <> ''
and rtrim(ltrim(lead_gender)) <> ''
and rtrim(ltrim(lead_interest)) <> ''
and lead_country in (select campaign_country
from client_campaigns
where campaignID = '#URL.ccampaignID#')
and leadID not in (select leadID
from lead_integration
where campaignID = '#URL.ccampaignID#')
order by
lead_tstamp desc
END
It points to the leadID not in ( .... part, if I delete this part it points the same error to and lead_country in ( ... part.
Can you please explain me whats happening?
Thanks.

An expression of non-boolean type specified in a context where a condition is expected, near 'Begin'

I am working on a hotel project and I need to check the availability of rooms. Here the logic is first need to check the room availability if it is not available then I need to check if checkout date entered by the customer is equal to the checkout date of any customer:
ALTER PROCEDURE [dbo].[customerdetails] (#CheckIn DATE, ...)
AS
BEGIN
BEGIN TRY
IF ( (SELECT Available
FROM rooms
WHERE roomtype = #RoomType) > 0 )
BEGIN
INSERT INTO Customerdetail
VALUES (#CheckIn, ...)
END
ELSE IF(SELECT *
FROM Customerdetail
WHERE RoomType = #RoomType
AND CheckOut = #CheckOut)
BEGIN
INSERT INTO Customerdetail
VALUES (#CheckIn, ...)
END
END TRY
BEGIN CATCH
DECLARE #ErrMessage NVARCHAR(max)
SET #ErrMessage=ERROR_MESSAGE()
RAISERROR (#ErrMessage,16,1)
END CATCH
END
But I get an error:
Msg 4145, Level 15, State 1
An expression of non-boolean type specified in a context where a condition is expected, near 'BEGIN'.
The problem is actually here, where you just say IF (get result):
ELSE IF(SELECT *
FROM Customerdetail
WHERE RoomType = #RoomType
AND CheckOut = #CheckOut)
This should be, I think, either IF (get result) = something or IF something (about result), e.g.:
ELSE IF EXISTS (SELECT *
FROM Customerdetail
WHERE RoomType = #RoomType
AND CheckOut = #CheckOut)
Also Paul is correct that this clause is not proper:
IF ( (SELECT Available
FROM rooms
WHERE roomtype = #RoomType) > 0 )
As written, if more than one row is returned, it will yield:
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
So, you should code this using EXISTS as he suggested.
You should also make sure you test this solution under a high level of concurrency, as Martin suggested in a comment.
Change:
IF ( (SELECT Available
FROM rooms
WHERE roomtype = #RoomType) > 0 )
to:
IF ( exists(SELECT Available
FROM rooms
WHERE roomtype = #RoomType) )

How to execute dynamic SQL in Teradata

Is there any way to submit dynamically generated SQL to Teradata? I've written a query that will create the code to denormalize a table. Right now, I am pulling the code down to my client (SAS) and resubmitting it in a second step. I am not familiar with either Teradata macros or procedures; would something like that work?
To illustrate, I have a table defined like this:
create multiset table MYTABLE
( RECID integer generated always as identity
( start with 1
increment by 1
minvalue -2147483647
maxvalue 2147483647
no cycle )
, SNAP_DATE date format 'YYYY/MM/DD'
, EMAIL_DATE date format 'YYYY/MM/DD'
, FREQ integer
)
unique primary index ( RECID )
The table is populated every day (SNAP_DATE) and is used to monitor changes to an email_date in another table. The following query returns the code that I can run to create my denormalized view:
select RUN_THIS
from (
select RUN_THIS, RN
from (
select 'select EMAIL_DATE ' (varchar(100)) as RUN_THIS
, 0 (int) as RN
) x
union all
select ', sum( case when SNAP_DATE = date '''
|| (SNAP_DATE (format 'yyyy-mm-dd') (char(10)) )
|| ''' then FREQ else 0 end ) as D'
|| (SNAP_DATE (format 'yyyymmdd') (char(8)) ) as RUN_THIS
, row_number() over ( partition by 1 order by SNAP_DATE ) as RN
from ( select distinct SNAP_DATE
from MYTABLE
where SNAP_DATE > current_date - 30) t1
union all
select RUN_THIS, RN
from (
select 'from MYTABLE group by 1 order by 1;' as RUN_THIS
, 10000 as RN
) y
) t
order by RN
I export the result of the above query to a file on my client, then turn around and submit that file back to Teradata. I'm hoping there is some way to store this complete definition in some Teradata object so it can be executed directly.
You may find success putting this in a stored procedure using the DBC.SysExecSQL command.
Here is an overly simplified example of a stored procedure in Teradata. Obviously in production would want an error handler defined to address things like invalid database objects. Furthermore, you could return the SQLSTATE back as a parameter to test for whether the stored procedure completed successfully or not.
CREATE PROCEDURE SYSDBA.CommentDatabase
(
IN P_Database VARCHAR(30),
IN P_Comment VARCHAR(255),
OUT MSG
)
MAIN: --Label
BEGIN
DECLARE P_SQL_TEXT VARCHAR(4000);
SET P_SQL_TEXT='COMMENT ON DATABASE '||P_DATABASE||' AS '''||P_COMMENT||'''';
CALL dbc.SysExecSQL (:P_SQL_TEXT);
SET MSG = 'Database '||P_DBNAME||' commented successfully!';
END;