Home > Software design >  Is it possible to execute the same query i'm using inside an IF EXISTS statement without repeat
Is it possible to execute the same query i'm using inside an IF EXISTS statement without repeat

Time:10-28

This really silly question just popped out of my mind out of curiosity; i'm still learning how to write better code in SQL and i just found myself in the situation where i have to check if the result of a query exists and then, if that was true, execute the same exact query to create a new table. The code is working and considering i'm not dealing with large amounts of data i have no problems of computation times but...it's simply ugly and i would like to make it more...appealing?

This is the code i'm refering to:

[...]

IF EXISTS  (SELECT  *value*, COUNT(*) AS Repetitions       
           FROM  *table*         
           GROUP BY *value*
           HAVING COUNT(*) > 1)

   SELECT *value*, COUNT(*) AS Repetitions
   INTO dbo.*newtable*
   FROM  *table*         
   GROUP BY *data*
   HAVING COUNT(*) > 1

ELSE

[...]

CodePudding user response:

Doing an exists first is unecessary.

Simply do

select <columns> into NewTable
From Table
where criteria;

if @@rowcount=0 
begin
  drop table NewTable;
end
else
begin
  /* Actions if table created */
end
  • Related