How to solve this SQL Server error I'm getting? - sql

As you can see below I am trying to execute a stored procedure by passing the two parameters, I get error like
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near 'C:\SQL_Backup\Test.bak'.
Code:
EXEC Proc_RestoreSQL_Database ('C:\SQL_Backup\Test.bak','DMTest')
Stored procedure being executed:
ALTER PROCEDURE [dbo].[Proc_RestoreSQL_Database]
#DISK nvarchar(1000),
#DBName varchar(1000)
AS
BEGIN
-- Create DB with script(DMUtilityTest)
CREATE DATABASE [#DBName]
-- restore
RESTORE DATABASE [#DBName]
FROM DISK = N'#DISK'
END

There is no need to CREATE the database if you are immediately going to restore it.
Just execute the restore directly. Do not wrap the database name parameter in [], nor the filename parameter in quotes '', you only need this if you are embedding the actual name, not parameters.
You should also use more sensible parameter types
CREATE OR ALTER PROCEDURE [dbo].[Proc_RestoreSQL_Database]
#DISK nvarchar(255),
#DBName sysname
AS
RESTORE DATABASE #DBName
FROM DISK = #DISK;
GO
This obviously assumes you are going to restore to the same location. You may want to pass new locations using MOVE TO #newFile
To execute it, again do not wrap in parenthesis (), just specify the parameter names
EXEC Proc_RestoreSQL_Database #DISK = 'C:\SQL_Backup\Test.bak', #DBName = 'DMTest';

Related

Create trigger in CREATE DATABASE stored procedure

We have a stored procedure that creates a database for each of our customers. This stored procedure runs in the context of master. A database name is passed in as a parameter to the stored procedure.
I am trying to modify the stored procedure to add a trigger to a table. I understand the stored procedure must switch to the new database to create triggers, so have appended the following to the stored procedure:
SET #str = ('USE ' + QUOTENAME (#db_name) + ' GO
CREATE TRIGGER ...')
EXEC (#str);
I get the error
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'GO'.
Msg 111, Level 15, State 1, Line 4
'CREATE TRIGGER' must be the first statement in a query batch.
Now I assume the second error is a consequence of the first, but I am blowed if I can work out how to switch databases in the stored procedure in order to create the triggers.
We are using SQL Server 2019. How do I create triggers in a create database stored procedure?
Another approach is to execute statement one after another.
DECLARE #str VARCHAR(MAX)
DECLARE #db_name SYSNAME = 'YourDBName'
SET #str = 'USE ' + QUOTENAME (#db_name)
EXEC (#str)
SET #str = 'CREATE TRIGGER ...'
exec (#str);
For completeness, as mentioned by #DaleK, adding the approach mentioned by Aaron Bertnard in the Stackexchange link
DECLARE #str VARCHAR(MAX)
DECLARE #db_name SYSNAME = 'master'
SET #str = 'EXEC '+ #db_name + '..sp_executesql #stmt=N''CREATE PROCEDURE usp_test AS SELECT 1;'''
exec (#str);

Creating Stored Proc to Insert into a View

I have created some new tables that I need to insert to on a semi-regular basis. Due to normalization I decided to build a view on top of the base tables to make reports more logical for myself and EU's. I got the bright idea to try to use a stored procedure to push inserts into the base tables via a different view. I can run the insert statement in SSMS successfully, but when I try to create it into a stored procedure it will run because it appears to think my insert is a function.
Here is the error:
Msg 215, Level 16, State 1, Procedure jedi.p_ForcePush, Line 12
Parameters supplied for object 'jedi.v_midichlorians' which is not a function. If the parameters are intended as a table hint, a WITH keyword is required.
Here is my script:
CREATE PROCEDURE jedi.p_ForcePush
#Field varchar(25) = NULL,
#Value varchar(250) = NULL
AS
BEGIN
SET NOCOUNT ON;
insert jedi.v_midichlorians (#field) values (#value)
END
GO
I have poured out my petition to the googles but haven't found a good solution. I have tried lots of different combo's in my syntax but nothing doing.
Any help is much appreciated! (ps-SQL 2012)
CREATE PROCEDURE jedi.p_ForcePush
#Field varchar(25) = NULL,
#Value varchar(250) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'INSERT INTO jedi.v_midichlorians (' + QUOTENAME(#field)
+ N') values (#value)'
EXECUTE sp_executesql #sql
, N'#Value varchar(250)'
, #Value
END
GO
When you pass #field param as a parameter sql server treats it as a string not an object name, Using QUOTENAME() wraps the passed column name in [] square brackets telling sql server explicitly that it is an object(Table, column) name.
On a side note If your View has only one underlying table on then use view to insert values other wise use the table name.
If you do have more then one underlying table in your View's definition and you want to insert data using view then you will need to create Instead of triggers.
Best option is to do all insert, update delete operation directly to tables, avoid using views and then triggers for view based on more then one underlying tables.
though you mentioned that insert stmts run fine in ssMS, can you confirm that the same insert stmt you ran in SSMS ? becaus ethere is an error in this stmt.
"insert jedi.v_midichlorians (#field)"
syntex is inccoect and column name should dnot have "#" right?
also is this view based on a single table ?

SQL Server - stored procedure

I am trying to create a stored procedure in SQL Server 2008. According to the parser, the syntax is OK. However, when I try to execute the stored procedure and pass actual values, the following error comes up:
Msg 201, Level 16, State 4, Procedure
SaveOneTimeDonation, Line 0
Procedure or function 'SaveOneTimeDonation' expects parameter '#donation', which was not
supplied.
Strange enough, the data is actually inserted into the table so I don't know why it is displaying this error.
How can I solve this problem please? Here is the code:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[SaveOneTimeDonation]
#donation float,
#date nvarchar
AS
INSERT INTO OneTime_Trans(Donation, Trans_Date) VALUES (#donation, #date)
exec SaveOneTimeDonation
The last line is executing the stored procedure. There it is missing the parameters.
exec SaveOneTimeDonation
Good luck!
Stored procedure is with parameters so at the end you should give parameters when you try to execute it.

How to force SQL Server 2005 objects to be recompiled NOW

According to this running sp_recompile forces the object to be recompiled the next time that it is run
I need it to be recompiled the moment I run the sp-recompile command, mainly to check for syntax errors and existence of objects on which the stored procedure depends.
--
on sql 2008 there's sys.sp_refreshsqlmodule module...
Probably the simplest way to do this is to re-deploy the stored procedure, which would (as far as I'm aware) remove the need to recompile the procedure.
Something along these lines:
SET #ProcedureName = 'SampleProcedure'
CREATE TABLE #ProcedureContent (Text NVARCHAR(MAX))
INSERT INTO #ProcedureContent
EXEC sp_helptext #ProcedureName
DECLARE #ProcedureText NVARCHAR(MAX)
SET #ProcedureText = ''
SELECT #ProcedureText = #ProcedureText + [Text] FROM #ProcedureContent
EXEC ('DROP PROCEDURE ' + #ProcedureName);
EXEC (#ProcedureText)
DROP TABLE #ProcedureContent

Execute stored proc with OPENQUERY

I have SQL Server 2008 with a linked Sybase server and I am trying to execute a stored procedure on the Sybase server using OPENQUERY. If I have a stored proc that doesn't take parameters it succeeds fine. If I have a stored proc with parameters it fails. I even tried a very basic stored proc that only took an int an that still failed. Below is the syntax I am using:
select * from
OPENQUERY([LINKSERVER],'exec database.user.my_stored_proc ''AT'',''XXXX%'',''1111'',1')
Msg 7357, Level 16, State 2, Line 3
Cannot process the object "exec database.user.my_stored_proc 'AT','XXXX%','1111',1". The OLE DB provider "ASEOLEDB" for linked server "LINKSERVER" indicates that either the object has no columns or the current user does not have permissions on that object.
As the proc will execute just fine without parameters, I don't think it is a permission issue.
This worked for me,
SELECT * FROM OPENQUERY(LOCALSERVER, 'SET FMTONLY OFF EXEC snr.dbo.GetAllSignals #controlRunId = 25, #experimentRunId = 26')
I was creating temporary tables, and that's why i got access denied
Here is more info http://www.sommarskog.se/share_data.html#OPENQUERY
I create a sp that doesn't return any value and it doesn't work.
Your SP in mysql have to return a value!
for example I do this in "mysql":
CREATE DEFINER=`root`#`localhost` PROCEDURE `MyPro`(IN `Name` VARCHAR(50), IN `Id` INT, OUT `Result` INT)
MODIFIES SQL DATA
BEGIN
DECLARE Result INT;
SET Result = 0;
INSERT into MyTable (Id,Name) VALUES(Id,Name);
SELECT Result;
END
That "Id" and "Name" is input parameter and "Result" is output parameter
and create linked server in SQL SERVER and call it like this:
select * from openquery
(
Test,'call mydb.MyPro(''Name'',''16'', #P0);'
)
It works for me :D
Linked Servers and OPENQUERY, Gems to MS SQL Server...that are wolves in sheep clothing. I've found the following solutions to work when dealing with parameters
If the SP is basically just SELECT statements, the move the same to a VIEW and just pass SQL statements via OPENQUERY.
Build the OPENQUERY as a string and then use execute_sql.
You could also see if it works to precede exec with SET FMTONLY ON:
OPENQUERY([LINKSERVER],'SET FMTONLY ON; exec database.user.my_stored_proc ''AT'',''XXXX%'',''1111'',1')
If you try this and it works, you should probably Google FMTONLY+OPENQUERY to get an idea of what it means.
Try this,
SELECT * FROM OPENQUERY(linked_server_name, 'SELECT postgres_procedure_name (parameters)');
I experienced a very similar issue, but my SP wasn't taking any parameters.
I tried experimenting with altering the query sent through the openquery to include 'SET NOCOUNT ON' and 'SET FMTONLY OFF' but this had no difference.
The only solution that worked for my stored procedure was dropping the existing version, and altering the code to specifically 'SET NOCOUNT ON'
After doing this I was able to successfully run my stored proc through my linked server connection.
First of all you have to add hard code text fields then you have to
replace it by your parameters value like FromDate,TillDate,EmpID,CompCode,0,DeptID,DesgId,LocationID,AtnType
DECLARE #startdate varchar(255) = '2019-12-17'
DECLARE #enddate varchar(255) = '2019-12-17'
Set #SQL = 'SELECT * FROM OPENQUERY(' + quotename(#LinkedServer) + ',' + '''' +
'SET FMTONLY OFF; exec [TAP].[dbo].[GetAttendanceList] ' + 'FromDate,TillDate,EmpID,CompCode,0,DeptID,DesgId,LocationID,AtnType,1'')'
You have to replace your parameters values shown below
set #SQL=REPLACE(#SQL,'FromDate',+''''+''''+#startdate+''''+'''')
set #SQL=REPLACE(#SQL,'TillDate',+''''+''''+#enddate+''''+'''')
set #SQL=REPLACE(#SQL,'CompCode',+''''+''''+#CompCode+''''+'''')
set #SQL=REPLACE(#SQL,'AtnType',+''''+''''+''''+'''')
if #EmpID is Null
begin
set #SQL=REPLACE(#SQL,'EmpID','null')
end
if #DeptID is Null
begin
set #SQL=REPLACE(#SQL,'DeptID','null')
end
if #DesgId is Null
begin
set #SQL=REPLACE(#SQL,'DesgId','null')
end
if #LocationID is Null
begin
set #SQL=REPLACE(#SQL,'LocationID','null')
end
print #SQL
exec ( #SQL)