I have a .sql file which includes lots of create function and other statements. I put go keyword between them but I got Incorrect Syntaxt Near Go error when I run this by stmt.executeupdate() in java. But when I run it in SSMS 17 I do not get any error. For example here:
GO
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[calculateweekday]')
AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' )) begin
DROP FUNCTION [dbo].[calculateweekday]
end
GO
create function [dbo].[calculateweekday]
(#inputDate datetime)
returns int as begin
Declare #result int;
Declare #tmp int
select #tmp = (select DATEPART(weekday, #inputDate))
if (#tmp != 1) begin
select #result = (select #tmp - 1)
end else begin
select #result = (select 7)
end
return #result
end
GO
I tried to put this in notepad++ too see if there is something wrong but it look likes same.
I also tried to change the encoding UTF-8 and ANSI but could not solve it. How can I solve this?
Related
We are using Postgres 13.0 version with Spring-Boot .sql file as an initial step.
I need to run an UPDATE script but only if the table itself already exists.
After some effort to understand what is the correct syntax I came with the following script:
ALTER TABLE IF EXISTS ONLY scm_repos ADD COLUMN IF NOT EXISTS token_id BIGINT;
DO '
BEGIN
IF EXISTS
(SELECT 1 FROM scm_repos WHERE id = 1)
THEN
UPDATE scm_repos repos SET token_id=(SELECT token_id FROM scm_orgs orgs WHERE repos.org_id=orgs.id);
END IF ;
END;
' ;
My intention is simple - to run the UPDATE script only if the scm_repos table does exists, but whatever I tried, I'm still getting the following error:
Failed to execute SQL script statement #5 of URL [jar:file:/app/cx-integrations-datastore.jar!/BOOT-INF/classes!/schema.sql]: DO '
BEGIN
IF EXISTS
(SELECT 1 FROM scm_repos WHERE id = 1)
THEN
UPDATE scm_repos repos SET token_id=(SELECT token_id FROM scm_orgs orgs WHERE repos.org_id=orgs.id);
END IF ;
END;
' ; nested exception is org.********ql.util.PSQLException: ERROR: relation "scm_repos" does not exist
Where: PL/pgSQL function inline_code_block line 3 at IF
What am I missing here?
13.0 has known unfixed bugs. 13.4 is the latest release of 13. There is almost never a good reason to run an old minor release version. Not that that seems to be relevant here.
But what you are missing here is that at the top level, EXISTS checks to see if a SELECT returns any rows. It does not check to see if tables mentioned in the FROM list of the SELECT exist or not, it assumes they do.
You could change your query so that it queries the catalog to see if the table exists, something like:
IF EXISTS
(SELECT 1 FROM pg_class where relname=$J$scm_repos$J$)
...
I'm using iBatis' ScriptRunner to execute scripts on an Oracle database. The first script is executed fine, but the second one which has triggers in it returns:
Cause: java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
The part of the script which returns this error is executed without any errors on SQL Developer:
.
.
.
create table MG_MSGALR
(
ID VARCHAR2(30) not null,
V_GRAV VARCHAR2(3),
constraint PK_MG_MSGALR primary key (ID) using index tablespace B_INDEX
);
CREATE OR REPLACE TRIGGER UC_JAR_LST_TRIGGER
BEFORE INSERT
ON UC_JAR_LST
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT UC_JAR_LST_SEQ.nextval INTO :NEW.ID FROM dual;
END;
/
CREATE OR REPLACE TRIGGER UC_UPD_LST_TRIGGER
BEFORE INSERT
ON UC_UPD_LST
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT UC_UPD_LST_SEQ.nextval INTO :NEW.ID FROM dual;
END;
/
Here's how I execute the script from my side:
Boolean procedure = StringUtils.endsWith(FilenameUtils.getBaseName(file.getName()), "procedure") || StringUtils.endsWith(FilenameUtils.getBaseName(file.getName()), "trigger");
runner.setSendFullScript(procedure);
runner.runScript(new FileReader(file));
I noticed that the Boolean procedure's value is always false even when the script has triggers in it, and so I tried to force ScriptRunner to send it as a full script just to see if it goes through or not and i got the following error instead:
CREATE OR REPLACE TRIGGER UC_UPD_LST_TRIGGER
BEFORE INSERT
ON UC_UPD_LST
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT UC_UPD_LST_SEQ.nextval INTO :NEW.ID FROM dual;
END;
/
. Cause: java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
Could somebody please tell me what am I doing wrong here? Should add some sort of delimiter in the file right before when the trigger creation is supposed to start (which is now at the very end of the file).
In case someone else runs into the same problem. When you have a hybrid script (which means it has both normal queries and procedures or triggers), and if you're trying to execute it using myBatis from Java, all you need to do is leave all of your procedures at the end of your script and put delimiters before and after them to let SQL know it should be executed as a block and not line by line. So here's how I added my delimiters:
-- Change the delimiter to '$'
-- #DELIMITER $
CREATE OR REPLACE TRIGGER UC_JAR_LST_TRIGGER
BEFORE INSERT
ON UC_JAR_LST
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT UC_JAR_LST_SEQ.nextval INTO :NEW.ID FROM dual;
-- Change the delimiter back to ';'
-- #DELIMITER ;
END;
-- Change the delimiter to '$'
-- #DELIMITER $
CREATE OR REPLACE TRIGGER UC_UPD_LST_TRIGGER
BEFORE INSERT
ON UC_UPD_LST
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT UC_UPD_LST_SEQ.nextval INTO :NEW.ID FROM dual;
-- Change the delimiter back to ';'
-- #DELIMITER ;
END;
And the execution ended without errors.
I have an anonymous pl/sql block in an sql file and I want to execute and assign values to it in Java. My sql block looks like this
DECLARE
someInput1 NUMBER(1);
someInput2 NUMBER(2);
someString1 VARCHAR(100);
BEGIN
someInput1 := ‘&1’;
someInput2 := ‘&2’;
--get name in table A
BEGIN
SELECT a.value INTO someString1
FROM TABLE_A a
WHERE a.id = someInput1;
END;
UPDATE TABLE_B b
SET b.someStringRow = someString1
WHERE b.someIntRow = someInput2;
COMMIT;
END;
/
exit;
What I am planning to do is load the sql file in a Java String, change ‘&1’ to ?1 and execute it as a CallableStatement. However, I am getting
PLS-00103: Encountered the symbol “” when expecting one of the following
begin function package pragma procedure subtype us <an identifier> <a double quoted delimited identifier> form current cursor
Error occured at lines in DECLARE section
Is my approach an acceptable solution, if yes, what may be wrong in my approach?
Are there other better solution for my problem? Thanks
you have to remove quote marks, and replace &1 with :1, and you should be fine, also, you will need remove '/' and exit; and they relate to sqlplus and not to pl/sql directly
I am working with TSP(Traveling salesmen problem) Solution in mysql.
for that we are going to develop procedure where i want to execute following query
-- variable coming from java
CREATE PROCEDURE solve_tsp(
inout ids varchar(21845);
)
begin
declare ret_ids varchar(21845);
-- some code
while length(ids) > 0 do
-- some assignment
SELECT to_id,distance into #l_tmp_id,#l_distance FROM mst_distance_matrix WHERE from_id =',#l_tmp_id,' AND
to_id IN (ids) -- ids is variable contains comma delimited string.
order by distance desc limit 1
-- concat value of to_id in ret_ids variable and then remove from ids variable
end while;
select ret_ids;
end;
You should look here.
http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html
Example:
PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
SET #a = 3;
SET #b = 4;
EXECUTE stmt1 USING #a, #b;
DEALLOCATE PREPARE stmt1;
See also:
Dynamic Query in MySQL
My MyBatis select is
// result map that sub-selects a folder
<resultMap id="beanWithFolderMap" type="com.example.BeanWithFolder">
<id column .../>
<association column="folder_id" property="folder" javaType="com.example.Folder" select="selectFolder"/>
</resultMap>
// folder sub-select
<select id="selectFolder" resultType="com.example.Folder">
SELECT
folder_id
name,
FROM folders
WHERE folder_id=#{folderId}
</select>
When no rows matching folder_id are found I want to return a special instance of Folder class.
Right now MyBatis returns null when it can't find a row. I want to return a Folder instance with folderId field set - since I know what I'm looking for I can at least set this field.
How to do it?
something like
SELECT
#{folderId} as folder_id,
name,
FROM folders
WHERE folder_id=#{folderId}
would be great, but I get the exception "Could not determine data type of parameter $1"
Function
If this query is used frequently, I would create a small function for it. That's probably fastest:
CREATE OR REPLACE FUNCTION f_foo(_folder_id int)
RETURNS TABLE (folder_id int, name text) AS
$func$
BEGIN
RETURN QUERY
SELECT f.folder_id, f.name
FROM folders f
WHERE f.folder_id = $1;
IF NOT FOUND THEN -- only if nothing was found
RETURN QUERY
VALUES ($1, NULL); -- columns must match!
END IF;
END
$func$ LANGUAGE plpgsql STABLE;
Call:
SELECT * FROM f_foo(133)
That's what you use in your script. Just like selecting from a table.
Plain SQL
There are other ways with plain SQL, preferably using NOT EXISTS. I guess a CTE would help:
WITH x AS (
SELECT folder_id, name
FROM folders
WHERE folder_id = $1;
)
SELECT * FROM x
UNION ALL
SELECT $1, NULL
WHERE NOT EXISTS (SELECT 1 FROM x);