Disable SQLCMD Syntax Check - sql

We sometimes write dataport scripts that rename tables or columns and have other complex logic. We also have SQL in IF statements referencing those old columns or tables. We have a standard to use IF statements to make our SQL Scripts multi run friendly.
However occasionally, even though the if statement evaluates to false, the code wrapped in the block errors out, I'm guessing because of a syntax check.
if 1 = 0
begin
select * from mydatabase.dbo.mytable; -- doesn't execute, but still errors because doesn't exist
end
Another weird thing is it isn't always consistent, sometimes it works fine.
Does anybody know if a way I can disable these sort of checks on a script by script basis.
Thanks
NOTE
I know people are going to say they tried a similar situation and it doesn't error. At first for me it didn't error in SSMS but it errored in SQLCMD.
sqlcmd MyTestScript.sql -r 1 -U user -P password
Then I put SSMS in SQLCMD mode Query -> CMDMODE and it still didn't give the error.
Then after rerunning a few times it started to error in both.

Try to use TRY-CATCH blocks, easy to use and elegant.
if 1 = 0
BEGIN TRY
select * from mydatabase.dbo.mytable;
END TRY
BEGIN CATCH
--error handling code
SELECT ERROR_MESSAGE()
END CATCH

I think execute_sql built in stored procedure can work around this.

Run the following code in your dev environment
DROP Procedure dbo.#TestProc
GO
CREATE Procedure dbo.#TestProc
AS
IF 1=0
BEGIN
SELECT 1 FROM XXXXX
END
ELSE
BEGIN
SELECT *
FROM Information_Schema.Tables
WHERE Table_Name = 'XXXXX'
END
GO
EXEC #TestProc
It compiles. It executes. It does not error out during either compilation or execution.
I am using SQL 2005.
As you can see from the results, there is no table called XXXXX.
I think your conditions are actually being met and the code is executing.
Edt
I went further than what I typed:
The stored proc gets created and runs for each one of the following
SELECT * FROM XXXXX.XXXXX /* owner XXXXX */
SELECT * FROM XXXXX.XXXXX.XXXXX /* database XXXXX */
The code bombs out when I fully qualify the name
SELECT * FROM XXXXX.XXXXX.XXXXX.XXXXX /* linked server XXXXX */
Now it LOOKS for the linked server and does not find one and throws an error.
Msg 7202, Level 11, State 2, Procedure #TestProc, Line 6
Could not find server 'XXXXX' in sys.servers.
Verify that the correct server name was specified.
If necessary, execute the stored procedure sp_addlinkedserver
to add the server to sys.servers.
Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure '#TestProc'.

A blunt instrument, but you can ignore errors.
:On Error ignore in the script?
-b and -V to ignore "severity < V" (Not tried it). Could be useful to detect "no object" errors but throw your own above V severity when there is really an error.
See SQLCMD in MSDN

Related

How to use SET OPTION within a DB2 stored procedure

I read (and tried) that I cannot use WITH UR in DB2 stored procedures. I am told that I can use SET OPTION to achieve the same. However, when I implement it in my stored procedure, it fails to compile (I moved around its location same error). My questions are:
Can I really not use WITH UR after my SELECT statements within a procedure?
Why is my stored procedure failing to compile with the below error
message?
Here is a simplified version of my code:
CREATE OR REPLACE PROCEDURE MySchema.MySampleProcedure()
DYNAMIC RESULT SETS 1
LANGUAGE SQL
SET OPTION COMMIT=*CHG
BEGIN
DECLARE GLOBAL TEMPORARY TABLE TEMP_TABLE AS (
SELECT 'testValue' as "Col Name"
) WITH DATA
BEGIN
DECLARE exitCursor CURSOR WITH RETURN FOR
SELECT *
FROM SESSION.TEMP_TABLE;
OPEN exitCursor;
END;
END
#
Error Message:
SQL0104N An unexpected token "SET OPTION COMMIT=*CHG" was found
following " LANGUAGE SQL
Here is code/error when I use WITH UR
CREATE OR REPLACE PROCEDURE MySchema.MySampleProcedure()
LANGUAGE SQL
DYNAMIC RESULT SETS 1
--#SET TERMINATOR #
BEGIN
DECLARE GLOBAL TEMPORARY TABLE TEMP_TABLE AS (
SELECT UTI AS "Trade ID" FROM XYZ WITH UR
) WITH DATA;
BEGIN
DECLARE exitCursor CURSOR WITH RETURN FOR
SELECT *
FROM SESSION.TEMP_TABLE;
OPEN exitCursor;
END;
END
#
line 9 is where the DECLARE GLOBAL TEMPORARY ... is
DB21034E The command was processed as an SQL statement because it was
not a valid Command Line Processor command. During SQL processing it
returned: SQL0109N The statement or command was not processed because
the following clause is not supported in the context where it is
used: "WITH ISOLATION USE AND KEEP". LINE NUMBER=9. SQLSTATE=42601
Specifying the isolation level:
For static SQL:
If an isolation-clause is specified in the statement, the value of that clause is used.
If an isolation-clause is not specified in the statement, the isolation level that was specified for the package when the package was bound to the database is used.
You need to bind the routine package with UR, since your DECLARE GTT statement is static. Before CREATE OR REPLACE use the following in the same session:
CALL SET_ROUTINE_OPTS('ISOLATION UR')
P.S.: If you want to run your routine not only 1 time in the same session without an error, use additional WITH REPLACE option of DECLARE.
If your Db2 server runs on Linux/Unix/Windows (Db2-LUW), then there is no such statement as SET OPTION COMMIT=*CHG , and so Db2 will throw an exception for that invalid syntax.
It is important to only use the matching Db2 Knowledge Centre for your Db2 platform and your Db2-version. Don't use Db2-Z/OS documentation for Db2-LUW development. The syntax and functionalities differ per platform and per version.
A Db2-LUW SQL PL procedure can use with ur in its internal queries, and if you are getting an error then something else is wrong. You have to use with ur in the correct syntax however, i.e in a statement that supports this clause. For your example you get the error because the clause does not appear to be valid in the depicted context. You can achieve the desired result in other ways, one of them being to populate the table in a separate statement from the declaration (e.g insert into session.temp_table("Trade ID") select uti from xyz with ur; ) and other ways are also possible.
One reason to use the online Db2 Knowledge Cenbtre documentation is that it includes sample programs, including sample SQL PL procedures, which are also available in source code form in the sample directory of your DB2-LUW server, in addition to being available on github. It is wise to study these, and get them working for you.

Can we use 'GO' multiple times in SQL Transaction?

Can We use GO statement mutiple times in a SQL Transaction. I am having a long T-SQL script and I want to run it in a SQL Transaction. If all goes well then I will commit otherwise will rollback.
But, While running that query I got error like 'create function must be the only statement in the batch'. As I am creating and dropping many Functions and Procedures in that.
I have not used GO anywhere in the script. My question is that - Can I use multiple times GO statement in that long script. Because, GO creates a batch and if batch executes successfully first time but fails next time then will rollback transaction statement be able to actually rollback that has been executed ?
Structure of my script looks like :
PRINT 'Transaction Started'
BEGIN TRY
BEGIN TRAN
Drop Function
....
....
Create Function
....
....
Drop Procedure
....
....
Lots of statements
....
....
COMMIT TRAN
PRINT 'Transaction Succeeded'
END TRY
BEGIN CATCH
PRINT 'Transaction Failed'
IF(##TRANCOUNT > 0)
ROLLBACK TRAN
END CATCH
I am creating this script to migrate some changes from newDB to oldDB in a single script.
You are mixing concepts. GO is not a Transact-SQL concept, not part of the language, and not understood by SQL Server. GO is the tools batch delimiter. sqlcmd.exe and SSMS both are using, by default, GO as the batch delimiter. The batch delimiter is used to identify the individual batches inside the SQL source file. The client tool sends to the server one batch at a time (of course, omitting the delimiter).
Transactions can span batches. TRY/CATCH blocks cannot. CREATE/ALTER statements must be the only statement in a batch (comments are not statements, and statements contained in a function procedure body are,well, contained).
Something similar to what you want to do can be achieved by starting a transaction and abortign the execution on first error (-b at sqlcmd.exe start, or use :on error exit in SSMS).
But doing DDL inside long transactions is not going to work. Specially if you plan to mix it with DML. Most corruptions I had to investigate come from this combination (Xact, DDL + DML, rollback). I strongly recommend against it.
The sole way to deploy schema updates safely is to take a backup, deploy, restore from backup if something goes wrong.
Note that what Dan recommends (dynamic SQL) works because sp_executesql starts a new, inner, batch. This batch will satisfy the CREATE/ALTER restrictions.
Note that GO is not a SQL keyword. It is a client-side batch separator used by SQL Server Management Studio and other client tools.
GO has no effect on transaction scope. BEGIN TRAN will start a transaction on the current connection. COMMIT and ROLLBACK will end the transaction. You can execute as many statements as you want in-between. GO will execute the statements separately.
As specified by MSDN:
A TRY…CATCH construct cannot span multiple batches.
So BEGIN TRY, END TRY, BEGIN CATCH, and END CATCH cannot be separated into separate batches by a GO separator. They must appear in the same query.
If you do try to include a batch separator in a TRY/CATCH statement like the invalid SQL below:
begin try
go
end try
begin catch
go
end catch
This will execute 3 different queries that return syntax errors:
1) begin try
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'begin'.
2) end try begin catch
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'try'.
3) end catch
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near 'catch'.
GO is a nice keyword to use. The GO will complete the last code block and continue on to the next block. Yes you can use multiple GOs in a statement to break it up into multiple batches. But it would be better to use try/catch logic with a combination of GOs since you are doing transaction based logic. https://msdn.microsoft.com/en-us/library/ms175976.aspx this site gives you some examples on how to use it and if you run into a hitch you can output that error and continue on if you choose.

Creating table in Firebird script causes "unsuccessful metadata update" with deadlock

I have the following script that I run using "isql -i scriptfile.sql":
CONNECT C:\Databasefile.fdb USER user PASSWORD password;
SET TERM !! ;
EXECUTE BLOCK AS BEGIN
IF (EXISTS(SELECT 1 FROM rdb$relations WHERE rdb$relation_name = 'MYTABLE')) THEN
EXECUTE STATEMENT 'DROP TABLE MYTABLE;';
END!!
SET TERM ; !!
CREATE TABLE MYTABLE
(
MYCOLUMN VARCHAR(14) NOT NULL
);
The very first time I run this (when the table does not already exist) the table is created as expected.
If I run the script again I get the following error:
Statement failed, SQLCODE = -607
unsuccessful metadata update
-STORE RDB$RELATIONS failed
-deadlock
After line 8 in file d:\myscript.sql
When the script exits, MYTABLE has been deleted and can no longer be found in the database.
If I run the script a third time the table is once again created and no errors are thrown.
Why can't the script both delete and then recreate a table?
DDL from PSQL is not allowed, using EXECUTE STATEMENT it is not directly forbidden, and usually possible, but still not wise exactly because of these kinds of problems. I am not exactly sure about the reasons, but part of it have to do with how DDL changes are applied in Firebird; the use of execute statement adds additional locks iirc which conflict with a subsequent DDL for the same table name.
Instead of dropping and creating this way, you should use the DDL statement RECREATE TABLE instead.
Note that the word deadlock in this error is actually a bit of a misnomer (there is no real deadlock).

Error in unreachable SQL Code

The following tsql fails:
IF OBJECT_ID('FDSCorp.XLFILES') IS NOT NULL
BEGIN
DELETE FROM FDSCorp.XLFILES;
INSERT INTO FDSCorp.XLFILES
SELECT DISTINCT * FROM dbo.XLFILES;
END
ELSE
exec sp_changeobjectowner XLFILES, FDSCorp;
Error:
The image data type cannot be selected as DISTINCT because it is not comparable.
Yes XLFilES has an image column, but in this case FDSCorp.XLFILES doesn't exist so that distinct code would never get to run.
This code is generated for each table in the database and I know that this section of the code will never be run on a table where it could fail due to the distinct issue.
I really don't want to have to overcomplicate the code checking for types which I can't use distinct with if that scenario could never happen in a real situation.
Is there some way I can bypass this check?
The only way to avoid the error is for you to prevent the server from "seeing" the code you don't want it to compile. Each batch is compiled entirely (including every statement, ignoring control flow) before execution starts:
IF OBJECT_ID('FDSCorp.XLFILES') IS NOT NULL
BEGIN
DELETE FROM FDSCorp.XLFILES;
exec sp_executesql N'INSERT INTO FDSCorp.XLFILES
SELECT DISTINCT * FROM dbo.XLFILES;';
END
ELSE
exec sp_changeobjectowner XLFILES, FDSCorp;
Now, when this batch is compiled, it won't attempt to compile the INSERT, since so far as this batch is concerned, it's just a string literal.

ORA:00900 Invalid sql statement

i created a procedure with 32 in argument,it sucessfully created.but when i am executing this in back end oracle the errror came ORA:00900 Invalid sql statement
Use:
SQL> alter procedure [your procedure name here] compile;
SQL> show errors
...to be able to diagnose the issue from the resulting error output.
Also look at view USER_ERRORS.
Sometimes, show errors does not show anything when in fact there are errors. Especially after alter compile.
Finally, re-compile in TOAD or SQL Developer and you can easily navigate to the error.
In Oracle SQL Developer you should execute it this way:
BEGIN
YOUR_PROCEDURE(PARAM1, PARAM2);
END;
If you use EXECUTE or EXEC (which work in SqlPlus) you get the ORA-00900 error.