Begin try drop vs if exists differences - sql-server

Can someone ELI5 (Explain Like I'm 5) the difference between using begin try drop and if exists when utilizing temp tables in SQL Server?
I have found that begin try drop seems to work better when used in outside programming languages, but have been told by a DBA that if exists is more efficient.
Just trying to understand the differences.
Thanks

Related

What is "dummy" in CREATE PROCEDURE statement

I'm doing investigation of code repo and find one thing that make me confused. SQL Server stored procedures are contained in a repo as a set of queries with following structure:
IF OBJECT_ID(N'[dbo].[sp_ProcTitle]', N'P') IS NULL
BEGIN
EXEC dbo.sp_executeSQL N'CREATE PROCEDURE [dbo].[sp_ProcTitle] AS dummy:;';
END
ALTER PROCEDURE dbo.sp_ProcTitle
#ParamOne int,
#ParamTwo date,
#ParamThree int
AS
SET NOCOUNT ON
-- some procedure body
END
Never before I saw AS dummy:; and now I'm a little confused, I can't find any good explanation what is it and how it works. Could anybody tell me what does it mean this statement? How it works? What is the reason to have it? Any thought would be good to hear. Or, please, advise me some link where I can find good explanation.
This is simply a label, such that could be used in a GOTO statement.
The word "dummy" is unimportant. It's simply trying to create the stored procedure if it doesn't exist, with a minimal amount of text. The content is then filled in with the ALTER.
Conceivably, the dummy text could later be searched for to see if any procedures were created and didn't have their content filled in, to check against failed deployments, etc.
Why do this? Well, it preserve the creation time of the stored procedure in metadata (which can be useful in administration or tracking down problems), and is compatible with versions of SQL Server that lack the CREATE OR ALTER... support.
This might make a little more sense if we add a little formatting to the CREATE:
CREATE PROCEDURE [dbo].[sp_ProcTitle]
AS
dummy:
This is, effectively, an empty procedure with a label called dummy. The user appears to be using this to ensure that the procedure exists first, and the ALTERing it. In older versions of SQL Server, such methods were needed because it didn't support CREATE OR ALTER syntax. As such, if you tried to ALTER a procedure that didn't exist the statement failed, and likewise if you try to CREATE a procedure that already exists it fails.
If you are on a recent version of SQL Server, I'd suggest changing to CREATE OR ALTER and getting rid of the call to sys.sp_executesql.

ALTER PROCEDURE doesn't work within IF statement [duplicate]

i have a situation where i want to check a certain column ( like version number) and then apply a bunch of ddl changes
trouble is i am not able to do it with in a IF BEGIN END block, since DDL statements require a GO separator between them, and TSQL wont allow that.
I am wondering if there is any way around to accomplish this
You don't need to use a full block. A conditional will execute the next statement in its entirety if you don't use a BEGIN/END -- including a single DDL statement. This is equivalent to the behavior of if in Pascal, C, etc. Of course, that means that you will have to re-check your condition over and over and over. It also means that using variables to control the script's behavior is pretty much out of the question.
[Edit: CREATE PROCEDURE doesn't work in the example below, so I changed it to something else and moved CREATE PROCEDURE for a more extended discussion below]
If ((SELECT Version FROM table WHERE... ) <= 15)
CREATE TABLE dbo.MNP (
....
)
GO
If ((SELECT Version FROM table WHERE... ) <= 15)
ALTER TABLE dbo.T1
ALTER COLUMN Field1 AS CHAR(15)
GO
...
Or something like that, depending on what your condition is.
Unfortunately, CREATE/ALTER PROCEDURE and CREATE/ALTER VIEW have special requirements that make it much harder to work with. They are pretty much required to be the only thing in a statement, so you can't combine them with IF at all.
For many scenarios, when you want to "upgrade" your objects, you can work it as a conditional drop followed by a create:
IF(EXISTS(SELECT * FROM sys.objects WHERE type='p' AND object_id = OBJECT_ID('dbo.abc')))
DROP PROCEDURE dbo.abc
GO
CREATE PROCEDURE dbo.abc
AS
...
GO
If you do really need conditional logic to decide what to do, then the only way I know of is to use EXECUTE to run the DDL statements as a string.
If ((SELECT Version FROM table WHERE... ) <= 15)
EXECUTE 'CREATE PROC dbo.abc
AS
....
')
But this is very painful. You have to escape any quotes in the body of the procedure and it's really hard to read.
Depending on the changes that you need to apply, you can see all this can get very ugly fast. The above doesn't even include error checking, which is a royal pain all on its own. This is why hordes of toolmakers make a living by figuring out ways to automate the creation of deployment scripts.
Sorry; there is no easy "right" way that works for everything. This is just something that TSQL supports very poorly. Still, the above should be a good start.
GO is recognised by client tools, not by the server.
You can have CREATEs in your stored procedures or ad-hoc queries with no GO's.
Multiple "IF" statements? You can test then for the success of subsequent DDL statements
Dynamic SQL? EXEC ('ALTER TABLE foo WITH CHECK ADD CONSTRAINT ...')?
As mentioned, GO is a client only batch separator to break down a single SQL text block into batches that are submitted to the SQL Server.

Sharepoint 2013 - Using Stored Procedure (CRUD)

I have below SP:
CREATE PROCEDURE [dbo].[ups_Ins_TblA] #ID int, #Comment nvarchar(max) AS
BEGIN
SET NOCOUNT ON
INSERT INTO [db_assets].[Claim]
(ID,Comment)
Values
(#ID,#Comment)
END
Basically, my question is, is there a way to call this in BCS Sharepoint(Business Connectivity Service) using out-of-the-box functionality? Can I further adjust the SP so that it can be supported with all 'CRUD' operations? Pls suggest ideas?
Note: I have made the table as simple as possible.
I don't want to make a straight-insert from the table because I have to join this to another table where document resides that's why I want to use SP.
I'd been spending almost 2-3days reading and still going on.. If anyone can direct me to the light, pls help? Thank you so much!!
This is a noob mistake. Apologies.
The answer is to write your stored procedure separately and assign it the each operation accordingly (Read Item, read List, Create, Update, Delete).
Yes, there will be 5 sp.
As long as the mapping of identifier is set appropriately, the creation of Lists will not have issue (with CRUD operation enabled).

Drop table from oracle database if table exist in sql statement [duplicate]

This question already has answers here:
Oracle: If Table Exists
(16 answers)
Closed 8 years ago.
I have to use an SQL statement to drop a table, it will crash if the table doesn't exist. Is it possible to use IF statement to drop the table
s.executeUpdate("DROP TABLE employee");
Oracle does not support a construct like drop table if exists my_table, which is apparently legal syntax in MySQL (and possibly other RDBMSs).
In a .SQL script, where you're running DDL to DROP and/or CREATE various objects, the Oracle standard is to drop the object, and ignore the error in cases where the object does not exist. If you wish, you can write code to check if the object exists (see DBA_OBJECTS view) to only drop if it exists.
from the s.executeUpdate, I gather that you're doing this in Java? If it was me, I'd just do the drop and ignore any not exists error.
assuming you have the right permissions, you can do something like the below
declare var_count int;
select count(*) INTO var_count
from all_tables where OWNER = [schema] and table_name = "EMPLOYEE";
if var_count > 0 then
begin
drop table employee;
end
adapt accordingly if you are doing this in front-end code instead of a pl/sql procedure.
Traditionally in pl/sql you can specify an exception section in the block, and catch the exception if the table is not there to drop.
See Oracle errors handling
This will resolve your problem, when the table doesn't exist no error will be thrown.
BEGIN
DROP TABLE employee;
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
I would use the following code:
s.executeUpdate("DROP TABLE IF EXISTS employee")
But depending on your verions, you could also use this:
IF OBJECT_ID('dbo.employee', 'U') IS NOT NULL
DROP TABLE dbo.employee
Answer taken from: here, also this seems like it might be a duplicate of the same post?
I would highly, highly recommend reading the SQL Documentation, and trying to do a bit more research before posting, but sense I see you are new, be sure to read the rules of posting here on StackOverFlow.

Can I recreate a temp table after dropping it?

Given:
code inside a stored proc:
select bleh
into #tblTemp
from FunctionThatReturnsTable('some','params')
-- do some stuff
drop table #tblTemp
-- Error on this command:
-- 'There is already an object named '#tblTemp' in the database.'
select bleh
into #tblTemp
from FunctionThatReturnsTable('some','other params')
Problem:
I can't recreate this temp table. My work around is to use #tmpTable1, #tmpTable2, #tempTable3 etc. Is there a way I can get around this? It would be nice just use one temp table each time.
If not, what is the reason for this?
As my comment reflected, I'm going to suggest that the answer is that you use a different #temp table name for each object that you create. It's kind of like saying to the doctor, "it hurts when I do this." His likely response is going to be, "stop doing that!"
The reason this is a problem is that SQL Server's parser attempts to parse the entire batch in one shot. It can clearly see that you are trying to create the same #temp table multiple times, but ignores the DROP command in between (I can't tell you exactly why that is, as I don't have access to the source code). This is the same reason you can't do this:
IF (1=1)
CREATE TABLE #foo(i INT);
ELSE
CREATE TABLE #foo(i VARCHAR(32));
The parser sees the two identical names, but can't really follow the IF/ELSE logic.
In addition to avoiding the problems multiple identically-named #temp tables causes the parser, another benefit to using unique names is that they can be re-used if you don't explicitly drop them. This will lighten the load on tempdb in terms of metadata / locking.
I ran into this problem with deleting+inserting column. The problem is probably with the parser, that it 'recognizes' the table on first create, and cannot see it was deleted.
I'd suggest using exec sp_executesql 'create table'
This is a feature by design and is clarified by Microsoft against Microsoft Connect Bug ID 666430
Please see a case study on the same at
temporary-table-could-not-be-re-created

Resources