Use stored procedure in values of an Insert statement - sql

I'm trying to use a stored procedure in an insert statement this is my code:
EXEC sp_executesql #statement=N'insert into Celulares_Empleados(CEL_IMEI,Empl_ID,FH_Asignacion,US_Asigno)
values (#imei, EXEC EMPLEADOS_LEGAJOS #legajo, #date, #usuario)',
#params=N'#imei nvarchar(15), #legajo nvarchar(41), #date datetime, #usuario nvarchar(5)',
#imei=N'353108089985778',
#legajo=N'USUARIO DE PRUEBA - Legajo: 1171',
#date='2020-06-18 22:56:08.367',
#usuario=N'admin'
But I get this message:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'EXEC'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ')'.
I also tried to put the Exec statement between ( ) but I get the same error.
Is there a way to do that?

You cannot call stored procedure as part of VALUES clause in INSERT. What you can do is, first execute the stored procedure and get the return value in a variable. Use the variable as part of your sp_executesql procedure call.
DECLARE #p_Empl_ID int
DECLARE #legajo NVARCHAR(41)= N'USUARIO DE PRUEBA - Legajo: 1171'
EXEC #p_Empl_ID = EXEC EMPLEADOS_LEGAJOS #legajo
EXEC sp_executesql #statement=N'insert into Celulares_Empleados(CEL_IMEI,Empl_ID,FH_Asignacion,US_Asigno)
values (#imei,#Empl_ID , #date, #usuario)',
#params=N'#imei nvarchar(15), #legajo nvarchar(41), #date datetime, #usuario nvarchar(5)',
#imei=N'353108089985778',
#Empl_ID = #p_Empl_ID ,
#date='2020-06-18 22:56:08.367',
#usuario=N'admin'
NOTE: Generally, best practice is to, return the execution status of the procedure as return value. If you want to get some scalar value out of procedure execution, it is preferred to use output parameter and use them in subsequent stages.
DECLARE #p_Empl_ID int
DECLARE #legajo NVARCHAR(41)= N'USUARIO DE PRUEBA - Legajo: 1171'
EXEC EMPLEADOS_LEGAJOS #legajo, #p_Empl_ID OUTPUT

Related

Msg 137, Level 15, State 2, Server ip-172-31-36-11, Line 2 Must declare the scalar variable "#Deptno"

My stored procedure (below) gives the following error:
Msg 137, Level 15, State 2, Server ip-172-31-36-11, Line 2 Must declare the scalar variable "#Deptno"
CREATE PROCEDURE EmployeesDept
#Deptno char(3)
AS
SELECT lastname AS Name
FROM Employee
WHERE workdept = #Deptno
GO
EXECUTE EmployeesDept #Deptno
GO
When it comes to executing a stored procedure you have to give the parameters values if you want it to work, and you can execute positionally or by name. You can put values in directly, or you can store values in variables and use those variables to give values to the stores procedure
--direct values
execute EmployeesDept 'abc', 0 --positional
execute EmployeesDept #Deptno='abc', #whatever=0 --named parameters
--values from variables
DECLARE #n CHAR(3) = 'abc';
DECLARE #i INT = 0;
execute EmployeesDept #n, #i --position based
execute EmployeesDept #Deptno = #n, #whatever = #i --name based
Named based parameters do not have to be in order, positional ones do
A better habit (for reasons of taking your skills to another DB) for CREATE PROCEDURE is like:
CREATE PROCEDURE EmployeesDept (
#Deptno char(3)
) AS
with parentheses around the argument list. For 2 or more args, separate with a comma. Example:
CREATE PROCEDURE EmployeesDept (
#Deptno char(3),
#whatever INT
) AS
Also get into the habit of ending each statement in a stored procedure with a semicolon

Passing a variable into sp_helptext

We want to dynamically pass variables into sp_helptext but because sp_helptext accept a variable passed into the colon; this is causing an error.
My query looks like so:
EXEC sp_helptext N'DatabaseName.dbo.SpName'; --- this works
DECLARE #spName VARCHAR(120) = 'spName'
EXEC sp_helptext N'DatabaseName.dbo.'+#spName+''
And the error:
Msg 102, Level 15, State 1, Line 53
Incorrect syntax near '+'.
The problem is that string operations are not supported for arguments.
This is easy enough to fix. Just do the string operations before the call:
DECLARE #spName VARCHAR(120) = 'spName';
DECLARE #fullName NVARCHAR(MAX) = N'DatabaseName.dbo.' + #spName;
EXEC sp_helptext #fullName;
This is for demonstration. If you are actually passing such values in, then you should be using QUOTENAME().

Stored procedure for a login with user and password as parameter

create procedure createacc(
#loginnaam nvarchar(30),
#wachtwoord nvarchar(30))
AS
CREATE LOGIN #loginnaam
WITH PASSWORD = #wachtwoord
CREATE USER #loginnaam FOR LOGIN #loginnaam
ALTER ROLE db_datareader ADD #loginnaam
Go
This gives me syntax errors while it works fine outside of the Stored Procedure.
Msg 102, Level 15, State 1, Procedure createacc, Line 5
Incorrect syntax near '#loginnaam'.
Msg 319, Level 15, State 1, Procedure createacc, Line 6
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Msg 156, Level 15, State 1, Procedure createacc, Line 8
Incorrect syntax near the keyword 'ADD'.
I would suggest using dynamic sql for this. Declare a nvarchar variable, put your statement inside it and execute that statement.
For example in your case:
DECLARE #statement NVARCHAR(MAX)
SET #statement = 'CREATE LOGIN ' + #loginnaam + ' WITH PASSWORD = '''+ #wachtwoord + ''' ;'
exec (#statement)
Above answer may be velnarable to SQL injection, it is concating SQL statement and then executing it.
Is there any way to pass password string as a parameter like example below
declare #query nvarchar(500)
declare #params nvarchar(500)
declare #passwordVal nvarchar(100)
set #passwordVal=N'Test#123'
set #query = 'Alter LOGIN [SqlUser] WITH password=#pass'
set #params = N'#pass NVARCHAR (100)';
EXECUTE sp_executesql #query,#params, #pass=#passwordVal
This query generates error
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '#pass'.
Better alternative answer to parameter is here
I am trying to create a stored procedure to create a login and a database user?

SQL Server and GUID?

I am trying to run this code :
exec myStoredProcedure
Cast('c5b48202-36af-4597-9780-5366d4188f55' AS uniqueidentifier),
744,
1,
'test',
'Chrysanthemum.jpg',
'2012-03-26 16:22:17',
1,
28402,
null
But I get the following exception
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'c5b48202-36af-4597-9780-5366d4188f55'.
Why? And how do I fix it?
You can't do a CAST when calling a stored procedure. Either you assign that to a variable before executing the sp, or just call it passing the VARCHAR as is (it probably will do the implicit cast just fine).
DECLARE #GUID UnIQUEIDENTIFIER
SET #GUID = 'c5b48202-36af-4597-9780-5366d4188f55'
EXEC myStoredProcedure #GUID, 744,
1,
'test',
'Chrysanthemum.jpg',
'2012-03-26 16:22:17',
1,
28402,
null
Apparently you cant use cast on the parameter list. I just wanted to be sure so I ran a little test:
create procedure myProc
#param1 uniqueidentifier
as
begin
select 1
end
exec myProc Cast('c5b48202-36af-4597-9780-5366d4188f55' AS uniqueidentifier) -- fails
exec myProc 'c5b48202-36af-4597-9780-5366d4188f55' --ok
You cannot use a calculation in a EXEC command.
You have to do like this:
DECLARE #guid uniqueidentifier
SET #guid = 'c5b48202-36af-4597-9780-5366d4188f55'
exec myStoredProcedure
#guid,
744,
1,
'test',
'Chrysanthemum.jpg',
'2012-03-26 16:22:17',
1,
28402,
null

Dynamic Function Issue

I am trying to create some dynamic DDL to build a function and when I run it, it keeps giving me an error. I am not sure what I am doing wrong with the format....I have tried a lot of different things and now it is just out of curiousity that I want to understand how to get it to work. Any input is greatly appreciated.
CODE:
DECLARE #SQL nvarchar(max) =
'ALTER FUNCTION dbo.GetFiscalDate()
RETURNS DATETIME
AS
BEGIN
DECLARE #RESULT DATETIME
SELECT #RESULT = #FY
RETURN #RESULT;
END'
,#FY datetime = '01/01/2016'
,#ParamDef nvarchar(50) = N'#FY datetime'
exec sp_executesql #SQL,#ParamDef,#FY
Gives me this error:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'FUNCTION'.
Msg 178, Level 15, State 1, Line 7
A RETURN statement with a return value cannot be used in this context.
This Code however...works:
DECLARE
#FY nvarchar(10) = '01/01/2015'
,#SQL nvarchar(max)
Select #SQL =
'ALTER FUNCTION dbo.GetFiscalDate()
RETURNS DATETIME
AS
BEGIN
DECLARE #RESULT DATETIME
SELECT #RESULT = ' + #FY + '
RETURN #RESULT;
END'
exec sp_executesql #SQL
What am I missing with this when I want to pass in params instead of concatenating them with the statement?
As usual I greatly appreciate all input.
Thanks,
S
parameters are used in execution plans so that you can reuse the execution plan, not in DDL statements, use your 2nd approach
I don't see where in your string you're including a call to your function.
Whatever sql you put in your string should exec directly in a query window, and altering a function and then listing the params wouldn't do it. You have to exec the function with the params listed in their normal syntax.
Why not pass the #FY variable as a parameter into the function?
I'm not sure what you're trying to do, but I wouldn't expect the approach you've described above to work.