How to Execute SQL Server Stored Procedure in SQL Developer? - sql-server

I've been given a user account to a SQL Server database that only has privileges to execute a stored procedure. I added the JTDS SQL Server JDBC jar file to SQL Developer and added it as a Third Party JDBC driver. I can successfully log in to the SQL Server database. I was given this syntax for running the procedure:
EXEC proc_name 'paramValue1' 'paramValue2'
When I run this as either a statement or a script, I get this error:
Error starting at line 1 in command:
EXEC proc_name 'paramValue1' 'paramValue2'
Error report:
Incorrect syntax near the keyword 'BEGIN'.
I tried wrapping the statement in BEGIN/END, but get the same error. Is it possible to call the procedure from SQL Developer? If so, what syntax do I need to use?

You don't need EXEC clause. Simply use
proc_name paramValue1, paramValue2
(and you need commas as Misnomer mentioned)

You are missing ,
EXEC proc_name 'paramValue1','paramValue2'

You need to do this:
exec procName
#parameter_1_Name = 'parameter_1_Value',
#parameter_2_name = 'parameter_2_value',
#parameter_z_name = 'parameter_z_value'

EXECUTE [or EXEC] procedure_name
#parameter_1_Name = 'parameter_1_Value',
#parameter_2_name = 'parameter_2_value',
#parameter_z_name = 'parameter_z_value'

I know this is the old one. But this may help others.
I have added SP calling function between BEGIN/END. Here is a working script.
ALTER Proc [dbo].[DepartmentAddOrEdit]
#Id int,
#Code varchar(100),
#Name varchar(100),
#IsActive bit ,
#LocationId int,
#CreatedBy int,
#UpdatedBy int
AS
IF(#Id = 0)
BEGIN
INSERT INTO Department (Code,Name,IsActive,LocationId,CreatedBy,UpdatedBy,CreatedAt)
VALUES(#Code,#Name,#IsActive,#LocationId,#CreatedBy,#UpdatedBy,CURRENT_TIMESTAMP)
EXEC dbo.LogAdd #CreatedBy,'DEPARTMENT',#Name
END
ELSE
UPDATE Department SET
Code = #Code,
Name = #Name,
IsActive = #IsActive,
LocationId = #LocationId,
CreatedBy = #CreatedBy,
UpdatedBy = #UpdatedBy,
UpdatedAt = CURRENT_TIMESTAMP
where Id = #Id

You need to add a , between the paramValue1 and paramValue2. You missed it.
EXEC proc_name 'paramValue1','paramValue2'

EXEC proc_name #paramValue1 = 0, #paramValue2 = 'some text';
GO
If the Stored Procedure objective is to perform an INSERT on a table that has an Identity field declared, then the field, in this scenario #paramValue1, should be declared and just pass the value 0, because it will be auto-increment.

There are two ways we can call stored procedure
CALL database name'. 'stored procedure name(parameter values);
example:- CALL dbs_nexopay_sisd1_dec_23.spr_v2_invoice_details_for_invoice_receipt_sub_swiss(1, 1, 1, 1);
From your MySQL workbench also you can do that.
i. Right-click on stored procedure.
ii. Send to SQL editor
iii. Procedure call.

If you simply need to excute your stored procedure
proc_name 'paramValue1' , 'paramValue2'...
at the same time you are executing more than one query like one select query and stored procedure you have to add
select * from tableName
EXEC proc_name paramValue1 , paramValue2...

The stored procedures can be run in sql developer tool using the below syntax
BEGIN
procedurename();
END;
If there are any parameters then it has to be passed.

Select * from Table name ..i.e(are you save table name in sql(TEST) k.
Select * from TEST then you will execute your project.

Related

SQL Server stored procedure only works with locally re-declared variables; not variables passed to the procedure

I have edited my SQL code blocks to more accurately show what is going on
Say I have a simple stored procedure:
CREATE PROCEDURE [DBO].[FOO]
(#VARIABLE VARCHAR(500))
AS
BEGIN
SELECT AVG(BAR)
FROM MYTABLE
WHERE THING = #VARIABLE AND RTRIM(LTRIM(THING)) <> ''
END
When I call this stored procedure from my classic ASP page; which in this case would be with:
Set foo = Server.CreateObject("ADODB.RecordSet")
curCmd = "Foo 'MYVARIABLE'"
foo.Open curCmd, connectionString
I get this error (on the same line as the page opens the foo object):
Arithmetic overflow error converting varchar to data type numeric.
If I call the stored procedure manually in the terminal (IDE?); then it works fine.
Also if I recreate the stored procedure as the following:
CREATE PROCEDURE [DBO].[FOO]
(#VARIABLE VARCHAR(500))
AS
BEGIN
DECLARE #VARIABLE2 VARCHAR(500) = #VARIABLE
SELECT AVG(BAR)
FROM MYTABLE
WHERE THING = #VARIABLE2 AND RTRIM(LTRIM(THING)) <> ''
END
Then the stored procedure runs fine.
I have tried dropping and recreating the stored procedure (without using the re-declaration trick), but it does not fix the issue.
*As an aside; there is validation on the data being inserted into the table to ensure that only numbers (integers) are being entered for the THING field. The THING field can also be blank; hence the where clause.
I basically have two questions:
Why does re-declaring the same variable type with the same data fix the issue?
Is there a way I can fix my problem without using this silly "re-declaration" trick?
Thanks in advance for any help with this.
I think you can get the same error if you use begin/end:
CREATE PROCEDURE [DBO].[FOO] (
#VARIABLE VARCHAR(500)
)
AS
BEGIN
DECLARE #VARIABLE2 VARCHAR(500) = #VARIABLE;
SELECT AVG(BAR) FROM MYTABLE WHERE THING = #VARIABLE2;
END;
Then, both statements will be part of the stored procedure body and you can work on fixing the data so it will work.

No result rowset is associated with the execution of this query

I am creating an Execute SQL task in SSIS 2016 which calls an insert stored procedure. I am trying to return the id of the newly created row in the output parameter but facing the following error.
No result rowset is associated with the execution of this query
I had set the SQL Server Profiler on to see what was generated and it was as follows
declare #p4 int
set #p4=NULL
exec sp_executesql N'Exec [dbo].[InsertPkgAudit] #P1,#P2',N'#P1 varchar(16),#P2 int OUTPUT','CoreReferenceETL',#p4 output
select #p4
If I execute the following it manually it works
DECLARE #auditId INT;
EXEC [dbo].[InsertPkgAudit] #packageName = 'CoreReferenceETL', #auditId = #auditId OUTPUT;
PRINT #auditId;
So it is clear that the stored procedure is fine but some problem with the way its called in SSIS. Could somebody help ?
The Execute SQL task contains the following statement
Exec [dbo].[InsertPkgAudit] #packageName =?, #auditId = ?
The parameter mapping is as follows
The result pane is as follows
The stored procedure is as follows:
CREATE Procedure [dbo].[InsertPkgAudit]
#packageName varchar(100),
#auditId int output
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[PkgAudit] ([PackageName], [StartTime])
VALUES (#packageName, GETDATE());
SET #auditId = SCOPE_IDENTITY();
END
The table structure is as follows
You have told SSIS that your procedure returns a result set. But it doesn't. It populates an OUTPUT parameter instead.
You can either change your proc to return a resultset, or you can modify the Execute task and
Specify No Result Set
Change the query to this:
`Exec [dbo].[InsertPkgAudit] #packageName =?, #auditId = ? OUTPUT`
I just had a similar issue and while looking for some sort of solution I came across this old post. I wasn't able to find the solution online but, here is how I resolved my issue. I hope this helps folks in the future.
If you really need to get the data passed via RowSet, you will need to select as
'ColumnName'.
Declare #fname varchar(50)
Declare #lname varchar(50)
set #fname ='John'
set #lname= 'Doe'
select #fname, #lname--without column name
select #fname as 'firstName', #lname as 'LastName'--with column name
Here is how they would show up in the results.
You can now map the result to proper variable.

Retrieve column definition for stored procedure result set that uses temp table

I am trying to retrieve column definitions for a stored procedure using the following query:
exec sp_describe_first_result_set #tsql = N'EXEC #return_value = [dbo].[foo]
#DATABASENAME = dbname,
#TABLENAME = tblname,
#DATEFROM = N''20170101'',
#DATETO = N''20170201'''
And I get the following response:
Msg 11526, Level 16, State 1, Procedure sp_describe_first_result_set, Line 1
The metadata could not be determined because statement 'INSERT INTO #Tables(CubeSchema,TableName,DateFilterColumn,SelectColumns) SELECT 'Col1','Col2' in procedure 'foo' uses a temp table
Is there a workaround for this issue?
Edit: I have not the rights to view and/or alter the stored procedures, so unfortunately solutions of this sort won't work.
Without altering your stored procedure the answer is MAYBE.
The option you are using ('sp_describe_first_result_set') wont work with the temp table, since you are using an INSERT statement.
If you would alter the INSERT statement to a SELECT INTO statement it might work for storing the data into the temp table, but you still wouldn't get your data out of it, since it isn't available. I am not sure about the internals of 'sp_describe_first_result_set', but it looks like it is using the SET FMTONLY ON option, which will fail because of the temp table.
So, if you want to avoid this, alter the stored procedure to use a table variable instead of a temp table (#table vs #table).
If you are not limited to SQL Server and you can program your way around this in a programming language (for example .Net using ADO.Net), you are able to use the GetSchemaTable method of the ExecuteReader result, like this:
var reader = sqlCommand.ExecuteReader();
var schemaTable = reader.GetSchemaTable();
Hope it helps!

How can I save a stored procedure which contains errors in SQL Server?

I want to save a stored procedure which contains errors according to SQL Server.
This is the procedure code:
Create PROCEDURE [Product].[JewelSearch]
#JewelItem bigint,
#JewelType nvarchar(50),
#JewelMate nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM Product.#JewelType
WHERE Material = #JewelMate OR Item# = #JewelItem;
END
The problem is that I have a Product schema, and I am taking the table name from my main application and saving it in #JewelType and in each search in main application the table name must be changed and each time their will be a different table name in #JewelType.
According to me the query is perfect but SQL Server does not allow me to execute it and save it. Is there a way that I can forcibly save this stored procedure? Hope you understand my question please help me if possible.
If it is SQL Server, something like this should work
Create PROCEDURE [Product].[JewelSearch]
#JewelItem bigint,
#JewelType nvarchar(50),
#JewelMate nvarchar(50),
#SQL nvarchar(max)
AS BEGIN
SET NOCOUNT ON;
SET #SQL = 'Select * From Product.'+#JewelType+' where Material = '+#JewelMate+' OR Item# = '+CAST(#JewelItem as nvarchar(50))+'; '
EXEC(#SQL)
END
This is untested as I am on my Mac, but you get the idea.
If you are going to use this, be aware of the dangers of dynamic SQL in relation to SQL Injection.
SQL Injection with Dynamic SQL - MSDN

quering remote database using sql server?

I have used sp_addlinkedserver to access the remote machines db now i am writing queries explicitly on database like,
select * from [server\instance].database.owner.tablename
Now with this,
[Server\instance] : this has to be provided explicitly
[database] : can we find databases on specified instance using query like ms_ForEachDB ?
[owner] : Can we find the database owner name using query ?
If these values are found using queries do we need to use EXEC() to execute this or we can still achieve it using nice queries ?
Thanks all,
The "nice" format you mention is simply a 4 part object reference.
select * from [server\instance].database.owner.tablename
3 part
select * from database.owner.tablename
2 part
select * from owner.tablename
If you want to dynamically change any of the server, db or schema values then you have one option:
EXEC (#sqlstring)
However, if you only access stored procs remotely...
DECLARE #RemoteSP varchar(500)
SET #RemoteSP = '[server\instance].database2.schema.proc2'
EXEC #RemoteSP #p1, #p2, #p3 OUTPUT
SET #RemoteSP = '[server\instance].database1.schema.proc1'
EXEC #RemoteSP #p4, #p5, #p6 OUTPUT
However, changing the components of the object reference makes no sense arguably: if you know you're going to query a table then just call that table in that database...
you should make a query string and then run it by exec() function.
getting server name :
SELECT ##SERVERNAME
getting current db name :
SELECT DB_NAME() AS DataBaseName
You do not have to use EXEC you could use something like select * from openquery(MyLinkedServer,#sql) THough i prefer EXEC(#sql) AT MyLinkedServer
But all work
If it happens that you need to use some sort of variable in your arguments(e.g. collect remote's server updates since yesterday):
DECLARE #yesterday NVARCHAR(20) = '2016-09-23 08:16:20';
DECLARE #sql NVARCHAR(MAX) = N'SELECT * FROM database.targetTable AS origin
WHERE origin.columnWithDateTime >'''+#yesterday+''';';
PRINT #sql;
EXEC(#sql) AT linkedServer
______
Where:
database.targetTable : For some reason SSMS 2008 R2 returns error if you describe it as [database].[targetTable], and i don't know why that happens.
#yesterday: Is the variable you want to insert (this case, a string containing datetime-like element)
PRINT #sql: Just to verify if the quotes are correctly placed.
columnWithDateTime: Should be a column with datetime format (e.g. "timestamp", or similar to the #yesterday variable format.
"OPENQUERY does not accept variables for its arguments.": See Here (MSDN: OPENQUERY (Transact-SQL)).

Resources