I am using SQL Server 2008 R2 and I want to create a stored procedure that deletes from two tables using a paramater (id).
This is the stored procedure:
CREATE PROCEDURE [dbo].[sp_deleteDecision]
#ID int
AS
DELETE FROM [dbo].[tblDecisionInvolvement] as di
WHERE di.DecisionId = #ID
DELETE FROM [dbo].[tblDecision] as d
WHERE d.Id =#ID
GO
This is the error I get when I try to create it:
Msg 156, Level 15, State 1, Procedure sp_deleteDecision, Line 6
Incorrect syntax near the keyword 'as'.
Msg 156, Level 15, State 1, Procedure sp_deleteDecision, Line 8
Incorrect syntax near the keyword 'as'.
Note that changing the DELETE FROM to
SELECT * FROM
it works.
Is it even possible to delete something using parameters?
Ty.
You aren't allowed to introduce an alias at that part of a DELETE statement - nor do you need one in this case:
USE ChessDb01
GO
CREATE PROCEDURE [dbo].[sp_deleteDecision]
#ID int
AS
DELETE FROM [dbo].[tblDecisionInvolvement]
WHERE DecisionId = #ID
DELETE FROM [dbo].[tblDecision]
WHERE Id =#ID
GO
For a more complex query, you might want to use an alias, but note that (confusingly), the DELETE will have two FROM clauses - and you can only introduce the alias in the second one:
DELETE FROM di
FROM [dbo].[tblDecisionInvolvement] di
inner join
AnotherTable tab
on
di.Column = tab.Column2
WHERE tab.Column99 = #Value
Related
I have two servers. I copied the table "Response_Master_Incident" on cadarchive server and duplicated it into the ucpdapps2 server and named it "Master_Incident_For_ProQA". When I duplicated it I only selected certain columns to duplicate (since I didn't need all the columns from "Response_Master_Incident").
Now I am trying to create a stored procedure to update the data from "Response_Master_Incident" to "Master_Incident_For_ProQA" pulling over only those select columns.
create procedure UpdateProQATable
as
begin
Select [ID]
,[Master_Incident_Number]
,[Response_Date]
,[Problem]
,[MethodOfCallRcvd]
,[CallTaking_Performed_By]
,[EMD_Used]
,[Determinant]
,[ProQa_CaseNumber]
,[ProQa_CaseNumber_Fire]
,[ProQa_CaseNumber_Police]
,[MachineName]
into Master_Incident_For_ProQA
from Response_Master_Incident where EMD_Used = '1'
end
When I run this stored procedure I get this error
"Msg 208, Level 16, State 1, Procedure UpdateProQATable, Line 4 [Batch Start Line 2]
Invalid object name 'Response_Master_Incident'."
How do I resolve this error. And is there a way to have the procedure update the table where the "Response_Date" is a date from yesterday and not all the data from the "Response_Master_Incident" table?
So I figured it out. I needed to go to Databases/Server Objects/Linked Servers and link the server that has the data I needed to pull over to the server that was getting the data.
After I did that I corrected my script as suggested in the above comment but also added script to delete all the data currently in the table, insert new data, and filtered the new data by the column of EMD_Used and the Response_Date as yesterdays date. After doing this the desired result was met.
delete from Master_Incident_For_ProQA
insert into [ucpdapps2].[ProQAUsage].[dbo].[Master_Incident_For_ProQA]
([ID]
,[Master_Incident_Number]
,[Response_Date]
,[Problem]
,[MethodOfCallRcvd]
,[CallTaking_Performed_By]
,[EMD_Used]
,[Determinant]
,[ProQa_CaseNumber]
,[ProQa_CaseNumber_Fire]
,[ProQa_CaseNumber_Police]
,[MachineName])
Select [ID]
,[Master_Incident_Number]
,[Response_Date]
,[Problem]
,[MethodOfCallRcvd]
,[CallTaking_Performed_By]
,[EMD_Used]
,[Determinant]
,[ProQa_CaseNumber]
,[ProQa_CaseNumber_Fire]
,[ProQa_CaseNumber_Police]
,[MachineName] FROM [cadarchive].[Reporting_System].[dbo].[Response_Master_Incident] where [EMD_Used] = 1 and [Response_Date] >= DATEADD(day, -1, CONVERT(date, getdate())) AND
[Response_Date] < CONVERT(date, getdate())
I want to create basically an update query on Open Office Base (the same way with Ms ACCESS).
Base does not typically use update queries (but see below). Instead, the easiest way to do an update command is to go to Tools -> SQL. Enter something similar to the following, then press Execute:
UPDATE "Table1" SET "Value" = 'BBB' WHERE ID = 0
The other way is to run the command with a macro. Here is an example using Basic:
Sub UpdateSQL
REM Run an SQL command on a table in LibreOffice Base
Context = CreateUnoService("com.sun.star.sdb.DatabaseContext")
databaseURLOrRegisteredName = "file:///C:/Users/JimStandard/Desktop/New Database.odb"
Db = Context.getByName(databaseURLOrRegisteredName )
Conn = Db.getConnection("","") 'username & password pair - HSQL default blank
Stmt = Conn.createStatement()
'strSQL = "INSERT INTO ""Table1"" (ID,""Value"") VALUES (3,'DDD')"
strSQL = "UPDATE ""Table1"" SET ""Value"" = 'CCC' WHERE ID = 0"
Stmt.executeUpdate(strSQL)
Conn.close()
End Sub
Note that the data can also be modified with a form or by editing the table directly.
Under some circumstances it is possible to create an update query. I couldn't get this to work with the default built-in HSQLDB 1.8 engine, but it worked with MYSQL.
In the Queries section, Create Query in SQL View
Click the toolbar button to Run SQL Command directly.
Enter a command like the following:
update mytable set mycolumn = 'This is some text.' where ID = 59;
Hit F5 to run the query.
It gives an error that The data content could not be loaded, but it still performs the update and changes the data. To get rid of the error, the command needs to return a value. For example, I created this stored procedure in MYSQL:
DELIMITER $$
CREATE PROCEDURE update_val
(
IN id_in INT,
IN newval_in VARCHAR(100)
)
BEGIN
UPDATE test_table SET value = newval_in WHERE id = id_in;
SELECT id, value FROM test_table WHERE id = id_in;
END
$$
DELIMITER ;
Then this query in LibreOffice Base modifies the data without giving any errors:
CALL update_val(2,'HHH')
See also:
https://forum.openoffice.org/en/forum/viewtopic.php?f=5&t=75763
https://forum.openoffice.org/en/forum/viewtopic.php?f=61&t=6655
https://ask.libreoffice.org/en/question/32700/how-to-create-an-update-query-in-base-sql/
Modifying table entries from LibreOffice Base, possible?
I tried implementing a call to Stored proc and the proc returns ID which will used later.
Everytime I execute I get the out parameter as -1. Below is my sample code:
OleDbCommand sqlStrProc = new OleDbCommand();
sqlStrProc.Connection = dbConn;
sqlStrProc.CommandText = "dbo.insert_test";
sqlStrProc.CommandType = CommandType.StoredProcedure;
sqlStrProc.Parameters.Add("#p_TestID", OleDbType.Integer, 255).Direction = ParameterDirection.Output;
sqlStrProc.Parameters.Add("#p_TestName", OleDbType.VarChar).Value = "Test";
sqlStrProc.Parameters.Add("#p_CreatedBy", OleDbType.VarChar).Value = "Test";
int personID = sqlStrProc.ExecuteNonQuery();
Row.outPersonID = personID;
personID is always -1. What am I doing wrong here. Please help..!!
Below is the stored proc code
CREATE PROCEDURE [dbo].[INSERT_TEST]
#p_TestID int OUTPUT,
#p_TestName varchar (50),
#p_CreatedBy varchar (100)
AS
SET NOCOUNT ON
INSERT INTO Test(
TestName,
CreatedBy)
VALUES
( #p_TestName,
#p_CreatedBy)
SELECT #p_TestID = SCOPE_IDENTITY()
-1 could mean that the stored procedure failed to execute as desired and the transaction was rolled back. You may want to look for any truncation issues since you have different sizes for the 2 input parameters but are using the same input. Also I assume you have proper code to open and close connections etc?
-1 returned value is an error produced during the execution of your SP, this is due to the following reasons:
SP Structure: everytime you are executing the SP it tries to create it again while it already exists. so you have to either make it an ALTER PROCEDURE instead of CREATE PROCEDURE or do the following:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INSERT_TEST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[INSERT_TEST]
GO
CREATE PROCEDURE [dbo].[INSERT_TEST]
#p_TestID int OUTPUT,
#p_TestName varchar (50),
#p_CreatedBy varchar (100)
AS
Database Connection (Table Name and Location): you have to specify withe the OLEDB the ConnectionString that connects you to the write DB. try to test the full Table path; like the following;
INSERT INTO [DATABASENAME].[SHCEMA].[TABELNAME](
Name,
CreatedBy)
VALUES
( #p_TestName,
#p_CreatedBy)
Define your SP as :
CREATE PROCEDURE [NAME]
AS
BEGIN
END
thought it is not a problem, but it is a proper way to write your SPs in terms of connection transactions,
Let me know if it works fine with you :)
Regrads,
S.ANDOURA
I'm using Firebird 2.x and I have made a stored procedure to insert a record if it doesn't exist and return its ID into a variable.
But when I execute, it turns out that the following error occurs:
Dynamic SQL Error. SQL error code = -104. Unexpected end of command - line 2, column 76.
Full source code of my SP following:
CREATE PROCEDURE INSERT_ADMIN_OFFICE
AS
DECLARE VARIABLE OFF_ID BIGINT;
DECLARE VARIABLE PER_ID BIGINT;
DECLARE VARIABLE EMP_ID BIGINT;
DECLARE VARIABLE AP_ID BIGINT;
BEGIN
IF (NOT EXISTS(SELECT * FROM OFFICE OFF WHERE OFF.DESCRIPTION LIKE '%Administrador%')) THEN
INSERT INTO OFFICE (DESCRIPTION) VALUES ('Administrador') RETURNING ID INTO :OFF_ID;
ELSE
SELECT OFF.ID FROM OFFICE OFF WHERE OFF.DESCRIPTION LIKE '%Administrador%' INTO :OFF_ID;
INSERT INTO PERSON (NAME, BIRTH_DATE, ADDRESS, DISTRICT, CITY, STATE) VALUES ('Intellitools Desenvolvimento de Software Ltda.', '01/01/2007', 'Rua Nunes Machado, 472 - Cj 503', 'Centro', 'Curitiba', 'PR') RETURNING ID INTO :PER_ID;
INSERT INTO USER_PASSPORT (PERSON_ID, USER_NAME, PWD, TYPE) VALUES (:PER_ID, 'intellitools', 123, 1);
INSERT INTO EMPLOYEE (OFFICE_ID, PERSON_ID) VALUES (:OFF_ID, :PER_ID) RETURNING ID INTO :EMP_ID;
INSERT INTO ACCESS_PROFILE (DESCRIPTION) VALUES ('Administrador Geral') RETURNING ID INTO :AP_ID;
INSERT INTO REL_EMPLOYEE_ACCESS_PROFILE (EMPLOYEE_ID, ACCESS_PROFILE_ID) VALUES (:EMP_ID, :AP_ID);
SUSPEND;
END
;
I notice that this error is because of the INTO on the INSERT but I can't find another way to do that.
I appreciate your help!
Just remove SUSPEND and your proc will execute like a charm. For a one time actions I would suggest EXECUTE BLOCK instead of creating stored procedure.
I cannot run the following SP
CREATE PROCEDURE SP_NYANSAT(
FORNAVN VARCHAR(30),
EFTERNAVN VARCHAR(30),
ADRESSE VARCHAR(50),
POSTNUMMER CHAR(4),
TELEFONNUMMER CHAR(8),
EMAIL VARCHAR(50))
AS
DECLARE VARIABLE ID INTEGER;
BEGIN
ID = GEN_ID(GEN_ANSAT_ID,1);
INSERT INTO MYTABLE (ID, FORNAVN, EFTERNAVN, ADRESSE, POSTNUMMER, TELEFONNUMMER, EMAIL) VALUES (:ID, :FORNAVN, :EFTERNAVN, :ADRESSE, :POSTNUMMER, :TELEFONNUMMER, :EMAIL);
END
The error I get is the following:
can't format message 13:896 -- message file C:\Windows\firebird.msg not found.
Dynamic SQL Error.
SQL error code = -104.
Token unknown - line 3, column 1.
CREATE.
Have you used Set Term before and after this code?
All commands in Firebird must be terminated with a semi-colon. If you want to create a stored procedure you need to be able to distinguish between the terminating semi-colon from the semi-colons inside the stored procedure.
Something like this:
SET TERM ^ ;
CREATE PROCEDURE SP_NYANSAT(
FORNAVN VARCHAR(30),
EFTERNAVN VARCHAR(30),
ADRESSE VARCHAR(50),
POSTNUMMER CHAR(4),
TELEFONNUMMER CHAR(8),
EMAIL VARCHAR(50))
AS
DECLARE VARIABLE ID INTEGER;
BEGIN
ID = GEN_ID(GEN_ANSAT_ID,1);
INSERT INTO MYTABLE (ID, FORNAVN, EFTERNAVN, ADRESSE, POSTNUMMER, TELEFONNUMMER, EMAIL) VALUES (:ID, :FORNAVN, :EFTERNAVN, :ADRESSE, :POSTNUMMER, :TELEFONNUMMER, :EMAIL);
END
^
SET TERM ; ^
Please notice how the declaration of the stored procedure is terminated with ^, thus ending the statement. After the declaration you also restore the terminating semi-colon.
On a side note, I would recommend to copy firebird.msg to the location the error you get tells you so you can see what is really happening.
EDIT:
If you wish you can check this link. There you can find a lot of information regarding Firebird + IBExpress, including SET TERM (page 81).
EDIT 2:
Just tried at home with IBExperts + Firebird and I had no problem creating the stored procedure. My guess is you are trying to do one of the following things:
You have opened an SQL editor and are trying to compile the code directly. That will not work because IBExperts thinks you are trying to run DSQL sentences. Stored procedures are created with PSQL sentences.
You are trying to use the "New procedure" utility (check buttons in the upper right side of the main menu) and pasted the whole code into the editor. That will not work because in that editor you only have to put the body code. Stored procedure name is set in a field on the upper right side of the window you opened. Parameters and variables are introduced by using the "Insert Parameter/Variable" button on the left side above the code editor. The SET TERM sentences are created automatically by IBExperts. You can check the resulting code in the DDL tab.
HTH