Code a SQL Server stored procedure to update vc_statusID - sql

I coded a stored procedure called vc_FinishVidCast that accepts an int as an input parameter that will be a vc_VidCastID that we will need to mark as finished. The act of finishing a VidCast means we must change its EndDateTime to be the current Date and Time (think GetDate()) and change the vc_StatusID to the vc_StatusID for the ‘Finished’ status.
alter procedure vc_FinishVidCast
(#vidCastID int, #finished int)
as
begin
update vc_VidCast
set vc_StatusID = #finished
where vc_VidCastID = #vidCastID
end
go
exec vc_FinishVidCast '859', '2'
DECLARE #newVC INT
INSERT INTO vc_VidCast (VidCastTitle, StartDateTime, ScheduleDurationMinutes, vc_UserID,vc_StatusID)
VALUES ('Finally done with sprocs', DATEADD(n, -45, GETDATE()), 45,
(SELECT vc_UserID FROM vc_User WHERE UserName = 'tardy'),
(SELECT vc_StatusID FROM vc_Status WHERE StatusText='Started')
)
SET #newVC = ##identity
SELECT *
FROM vc_VidCast
WHERE vc_VidCastID = #newVC
EXEC vc_FinishVidCast #newVC
SELECT * FROM vc_VidCast WHERE vc_VidCastID = #newVC
I get an error:
Msg 201, Level 16, State 4, Procedure vc_FinishVidCast, Line 179
Procedure or function 'vc_FinishVidCast' expects parameter '#finished', which was not supplied.

You may want to try something like below:
DECLARE #Finished_ID INT
SELECT #Finished_ID = vc_StatusID FROM vc_Status WHERE StatusText='FInished'
EXEC vc_FinishVidCast #newVC,#Finished_ID

Related

transact sql - can't select from variable

I'm trying to take the ID of a new record inserted into TABLE A and use it in a subsequent insert.
But I'm getting an error saying that the newUserId variable isn't declared.
it's actually a table variable.
The code looks like this;
USE Acme;
GO
DECLARE #userPrincipalName VARCHAR(100),
#displayName VARCHAR(100),
#domainName VARCHAR(100),
#tId INT,
#uname VARCHAR(100);
DECLARE #newUserid TABLE (
id INT
);
-- FILL ME IN
SET #domainName = 'mydomain.org';
SET #userPrincipalName = 'ppan#mydomain.org';
SET #displayName = 'Pan, Peter';
SET #tId=4;
SET #uname = 'ppan';
INSERT INTO dbo.User
(column list)
OUTPUT Inserted.ID INTO #newUserId
SELECT '', #domainName, getutcdate(), #userPrincipalName, #displayName, other fields
-- Create New Profile Using NewID ** THIS IS WHERE IT DIES
INSERT INTO dbo.UserProfile
SELECT #newUserId.id,
'{}', GETDATE(), getdate(), ''
The specific error is:
8:55:51 AMStarted executing query at Line 1
Commands completed successfully.
8:55:51 AMStarted executing query at Line 3
Msg 137, Level 16, State 1, Line 36
Must declare the scalar variable "#newUserid".
Total execution time: 00:00:00.017
I've abbreviated the code for the sake of this post but line 36 is where I'm referencing SELECT #newUserId.id
Any tips would be appreciated.
Thanks
Because #newUserId is a table variable you can't select it as a variable.
you can try to use INSERT INTO ....SELECT ... FROM
INSERT INTO dbo.UserProfile
SELECT id, '{}', GETDATE(), GETDATE(), ''
FROM #newUserId

How can i execute a stored procedure inside another stored procedure in SQL Server?

I´m working with SQLServer and I have two storedprocedures
The first one:
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
DECLARE #FECHAFIN AS datetime;
SET #FECHAFIN = #FECHAINICIO + '23:59:59.999'
-- Insert statements for procedure here
SELECT
HC.idCorrida AS Referencia,
T.part AS Parte,
T.idTrabajo AS Trabajo,
HC.cantidadFabricado AS Piezas,
HC.cantidadRechazado AS Rechazo,
CONVERT(varchar(8), HC.tiempoProduccion) AS TiempoDeProduccion,
CONVERT(varchar(8), HC.tiempoMuerto) AS TiempoMuerto,
HC.fechaInicio AS Fecha,
U.nombreUsuario AS Usuario,
MA.nombre AS NombreMaquina,
TR.nombre AS NombreTripulacion,
TXM.idTurno AS Turno,
FROM [Produccion].[HistorialCorridas] AS HC
INNER JOIN [Produccion].[Trabajos] AS T
ON HC.idTrabajo = T.idTrabajo
INNER JOIN [Administracion].[Usuarios] AS U
ON U.idUsuario = HC.idUsuario AND U.idTripulacion = #IDTRIPULACION
INNER JOIN [Administracion].[Tripulaciones] AS TR
ON U.idTripulacion = TR.idTripulacion
WHERE HC.idTurnoXMaquina = #IDTURNOXMAQUINA
AND HC.fechaInicio >= #FECHAINICIO AND HC.fechaInicio <= #FECHAFIN
GROUP BY HC.idCorrida, T.part, T.idTrabajo, HC.cantidadFabricado, HC.cantidadRechazado,
HC.tiempoProduccion, HC.tiempoMuerto, HC.fechaInicio, U.nombreUsuario, MA.nombre, TR.nombre, TXM.idTurno
END
The second one:
BEGIN
SET NOCOUNT ON
SELECT
CONVERT(VARCHAR(8), DATEADD(SECOND,SUM(DATEDIFF(SECOND, '00:00:00', TiempoMuerto)),0),114) AS TotalTiempoMuerto,
P.etiqueta AS TipoParo
FROM [Produccion].[TiemposMuertos]
INNER JOIN [Administracion].[ParosXMaquina] AS PM
ON PM.id = idParoXMaquina
INNER JOIN [Administracion].[Paros] AS P
ON P.idParo = PM.idParo
WHERE idCorrida = #IDCORRIDA
GROUP BY P.etiqueta
END
The second one receives as a parameter a field called Referencia from the first stored procedure. What I want to do, is execute the second stored procedure from the first one, passing that parameter.
How could I achieve this? Is it possible to get the result in just one query?
Thanks in advance!!!
To call a PROCEDURE from another PROCEDURE that returns a value as output, you must use the out keyword for the output, which may be a table or other data type.
The following two procedures are defined.
In test1 procedure, the return parameter is specified with out.
In the second procedure, the first procedure is called as follows:
DECLARE #result int
EXEC test1 #result OUTPUT
CREATE PROCEDURE test1
(#outID int output)
AS
BEGIN
SET #outID = (select top 1 ID from table1)
END
CREATE PROCEDURE test2
AS
BEGIN
BEGIN
DECLARE #result int
EXEC test1 #result OUTPUT
SELECT ID from table2 where ID = #result
END;
END
GO
EXEC test2

Passing Variable from stored procedure to another

I have a stored procedure that I need pass the parameter from one to the other procedure and have it display as an output. I am declaring the following in the header of my procedure [xxx].[zzzz_ERP_Cyyyyy]
DECLARE #ProcedureLogRowKey INT
DECLARE #ProcedureRecordCount INT
DECLARE #ProcedureStartDateTime DATETIME
DECLARE #ProcedureLog_Note NVARCHAR(100)
EXEC [XXX].[spciProcedurePerformanceStartRecord_help]
'.[xxx].[zzzz_ERP_Cyyyyy]',
1,
#ProcedureStartDateTime,
'Contract Check',
#ProcedureLogRowKey OUTPUT
I am getting the following error:
Msg 515, Level 16, State 2, Procedure spciProcedurePerformanceStartRecord_help, Line 33 [Batch Start Line 17]
Cannot insert the value NULL into column 'YSTRTDTT_0', table '000.xxx.YPERLOG'; column does not allow nulls. INSERT fails.
Here is the procedure that I am getting the variable from to pass into my procedure [xxx].[zzzz_ERP_Cyyyyy]
CREATE PROCEDURE [xxx].[spciProcedurePerformanceStartRecord_help]
(#ProcedureName VARCHAR(200),
#ProcedureRecordCount INT = 1,
#ProcedureStartDateTime DATETIME = GETDATE,
#ProcedureLog_Note NVARCHAR(100),
#ProcedureLogRowKey INT OUTPUT --- I am passing this into my proc and
displaying it as output
)
AS
BEGIN
-- Set Default return for #ProcedureLogRowKey, used if logging is not turned on.
SET #ProcedureLogRowKey = -1;
-- Check to see if performance logging is enabled
IF EXISTS(SELECT ROWID FROM LIVE.YPERCON
WHERE YPROCNM_0 = #ProcedureName AND YLOGENA_0 = 2)
BEGIN
INSERT INTO xxx.YPERLOG (YROWKEY_0, YPROCNM_0, YRECCNT_0, YSTRTDTT_0, YENDDTT_0, YLOGNOTE_0,
YDURMS_0, CREDATTIM_0, UPDDATTIM_0, AUUID_0, CREUSR_0, UPDUSR_0)
SELECT
ISNULL(MAX(YROWKEY_0), 0) + 1,
#ProcedureName, #ProcedureRecordCount, #ProcedureStartDateTime,
'1753-01-01',
#ProcedureLog_Note, 0,
GETDATE(), GETDATE(), NEWID(), 'admin', 'admin'
FROM
xxx.YPERLOG
SELECT #ProcedureLogRowKey = ISNULL(MAX(YROWKEY_0), 0)
FROM xxx.YPERLOG
END
ELSE
BEGIN
DECLARE #Count integer
SELECT #Count = COUNT(0)
FROM LIVE.YPERERR
WHERE YPROCNM_0 = #ProcedureName
IS ISNULL(#Count, 0) = 0
INSERT INTO LIVE.YPERERR (YPROCNM_0, YREQDT_0, YLASTDT_0, YERRMSG_0,
CREDATTIM_0, UPDDATTIM_0, AUUID_0, CREUSR_0, UPDUSR_0)
VALUES (#ProcedureName, GETDATE(), '1753-01-01', 'Controller not defined or active',
GETDATE(), GETDATE(), NEWID(), 'admin', 'admin')
ELSE
UPDATE xxx.YPERERR
SET YLASTDT_0 = GETDATE()
WHERE YPROCNM_0 = #ProcedureName
END
END
Thanks in advance.
The issue is in procedure [xxx].[spciProcedurePerformanceStartRecord_help] with parameter #ProcedureStartDateTime DATETIME. You should set its default value this way:
In declaration set default value as NULL
#ProcedureStartDateTime DATETIME = NULL
It would look like tihs
CREATE PROCEDURE [xxx].[spciProcedurePerformanceStartRecord_help]
(
#ProcedureName VARCHAR(200)
,#ProcedureRecordCount INT = 1
,#ProcedureStartDateTime DATETIME = NULL
,#ProcedureLog_Note NVARCHAR(100)
,#ProcedureLogRowKey INT OUTPUT
)
AS
BEGIN
-- procedure's body
END
Inside procedure, at the beginning, check if #ProcedureStartDateTime parameter's value is NULL and if it is, set its value to GETDATE().
SET #ProcedureStartDateTime = ISNULL(#ProcedureStartDateTime, GETDATE())
You have declared DECLARE #ProcedureStartDateTime DATETIME and did not set any value to it. so, it is having NULL value and you are passing NULL value to the procedure execution
EXEC [XXX].[spciProcedurePerformanceStartRecord_help]
'.[xxx].[zzzz_ERP_Cyyyyy]',
1,
#ProcedureStartDateTime, -- NULL value passed here
'Contract Check',
#ProcedureLogRowKey OUTPUT
As the target column 'YSTRTDTT_0', table '000.xxx.YPERLOG', does not allow NULLs, you are getting error.

Procedure or function 'Test' expects parameter '#ID', which was not supplied

I am new to understanding stored procedures. I am dealing with one similar to this:
CREATE PROCEDURE [Test]
(
#ID int,
#month int,
#Low int,
#standard float = 0
)
AS
IF EXISTS (SELECT 1 FROM [Table1] WHERE ID = #ID AND
month = #month AND TYPE = 'S' AND TYPEID = #Low)
BEGIN
UPDATE [Table1] SET
Add = #standard
WHERE ID = #ID AND month = #month AND TYPE = 'S' AND TYPEID = #Low
END
ELSE
BEGIN
INSERT INTO [Table1] (ID, month, Add, TYPE, TYPEID)
VALUES (#ID, #month, #standard, 'S', #Low)
END
GO
Which runs from this table:
ID Month Add Type TypeID
333 feb 0 T 111
333 feb 4 S 111
333 feb -2 K 111
But i receive this error:
'Procedure or function 'Test' expects parameter '#ID', which was not supplied.'
When i try and execute the procedure
Can someone advise me on whats going on here with the error here and what i can do to fix it? I have included ID so im not quite sure why that is creating an error. thanks
I call the procedure like this:
USE [DB1]
GO
DECLARE #return_value int
EXEC #return_value = [Test]
SELECT 'Return Value' = #return_value
GO
Do this: In SQL Server Management Studio, in the Object Explorer pane, right click on your stored procedure and choose "Script Stored Procedure as ->", "EXECUTE To ->", and then "New Query Editor Window". This will build a SQL statement for you that will properly execute your stored procedure when supplied with the proper parameter values.

Multiple parameters error while creating function in SQL Server

I created a function, now rather passing static value I want to add parameter in the function but after calling function it start throwing an error:
Procedure or function dbo.hello has too many arguments specified.
Function :
Create Function dbo.hello
(#InputstartDate Date, #InputendDate Date)
Returns #attendanceTemp table(STUD_NAME VARCHAR(50),
ATTD_DATE DATE ,
attd_DATEs DATE,
Attendance VARCHAR(20))
As
Begin
Declare #startDate DATE
SET #startDate = #InputstartDate
Declare #endDate Date
SET #endDate = #InputendDate
Declare #dateDifference INT
SET #dateDifference = DATEDIFF(day, #startDate,#endDate) ;
Declare #count INT
SET #count = 0
DECLARE #myTable TABLE (STUD_ID int,
countdd int,
STUD_NAME varchar(50),
AttDate Date
)
While #count <= #dateDifference
Begin
Insert Into #myTable (STUD_ID, countdd, STUD_NAME, AttDate)
Values (1, 123, 'HAIDER', #startDate)
Set #count = #count +1
Set #startDate = DATEADD(day, 1, #startDate)
End
Insert Into #attendanceTemp
Select
tb.STUD_NAME, ATTD_DATE, tb.AttDate,
Case
When att.DETAIL Is Null
Then 'ABSENT'
When att.DETAIL = 'ATTENDACE'
Then 'PRESENT'
End As Attendance
from
#myTable tb
Left Join
ATTENDANCE att on tb.AttDate = att.ATTD_DATE
Where
att.STUD_ID = 1 or att.STUD_ID IS NULL
Return
END
Calling the function:
select *
from dbo.hello('2014-04-01', '2014-04-10');
Error:
Procedure or function dbo.hello has too many arguments specified
Possibly you first created the function with only one parameter.
Then made changes to the 'create function' script, and forgot to deploy?
I would;
1. DROP FUNCTION dbo.hello
2. CREATE FUNCTION dbo.hello, with you script
3. Try executing your function again.
The function seems to work fine (Though I cannot run a full test due to not having table 'ATTENDANCE')