Checking if name already exists and also type of name in SQL Server - sql

I am checking for if name exist in the stored procedure. So basically checking if attr_name exists in the ibui_attribute table.
Here the attr_name can be either of the two types. There is column in the table called is_group that tells you if the attribute is a group or an attribute. I need to throw the error accordingly and hence written and if else condition. Do I need to write a query again to check if the attribute is group or an attribute for the if else condition or can I do that in the if exist SQL statement that has been written
CREATE PROCEDURE [IBT].[save_ibui_attribute]
#p_attr_id INT = NULL,
#p_is_group BIT = 0,
#p_attr_name VARCHAR (20),
#p_attr_desc VARCHAR (250),
#p_parent_attr_id INT,
#p_attr_level VARCHAR (20),
#p_attr_data_type VARCHAR (8),
#p_last_updt_user_nm VARCHAR (30) = NULL,
#p_last_updt_dtime DATETIME = NULL,
#debug AS BIT = 0
AS
BEGIN
BEGIN TRY
SET NOCOUNT ON;
DECLARE
#logfile VARCHAR (MAX),
#msg VARCHAR (255);
SET #msg = 'IBT.save_ibui_attribute Starts';
IF #debug = 1
BEGIN
SELECT 'IBT.save_ibui_attribute DEBUG START';
END;
IF #p_attr_id IS NULL
BEGIN
IF EXISTS (SELECT attr_name
FROM IBT.ibt_attribute
WHERE UPPER(attr_name) = UPPER(#p_attr_name))
BEGIN
IF ATTRIBUTE
RAISERROR ( 50001, 16, 1, 'ERROR! : New attribute has a name that is already in use. Please use a different attribute name' );
ELSE
IF GROUP
RAISERROR (50001, 16, 1, 'ERROR! : New group has a name that is already in use. Please use a different group name' );
END;
END;
END;
Do I do something like this
declare #isGroup bit;
IF #p_attr_id IS NULL
BEGIN
SET #isGroup = (SELECT is_group
FROM IBT.ibt_attribute
WHERE UPPER(attr_name) = UPPER(#p_attr_name))
IF #isGroup = 0
RAISERROR ( 50001, 16, 1, 'ERROR! : New attribute has a name that is aleady in use. Please use a different attribute name' );
ELSE IF #isGroup = 1
RAISERROR ( 50001, 16, 1, 'ERROR! : New group has a name that is aleady in use. Please use a different group name' );
END;
END;

Related

Creating Stored Procedures by using if else statement giving compilation error

New to DB2. Version 11. While creating stored procedure it gives an error Incorrect syntax near 'FROM' expected: BULKINFO
CREATE PROCEDURE My_StrProc
( IN #rollNumber Varchar(18),
IN #studentType Varchar(3),
OUT #studentID Varchar(15),
OUT #oldStudentType Varchar(4) ,
OUT #oldBranch Varchar(3) ,
OUT #newStudentType Varchar(4) ,
OUT #newBranch Varchar(4)
)
BEGIN
IF #studentType IS NOT NULL
THEN
Select
#studentID = REGISTRATION_NO,
#oldStudentType = OLD_STUD_TYPE,
#oldBranch = OLD_BRANCH,
#newStudentType = NEW_STUD_TYPE,
#newBranch = NEW_BRANCH
From
Migrated_Student
Where
OLD_STUDENT_NUM = #rollNumber and
ACTIVE = 'P';
ELSE
Select
#studentID = REGISTRATIONNO,
#oldStudentType = OLD_STUD_TYPE,
#oldBranch = OLD_BRANCH,
#newStudentType = NEW_STUD_TYPE,
#newBranch = NEW_BRANCH
From
Migrated_Student
Where
OLD_STUDENT _NUM = #rollNumber and
OLD_ STUDENT _TYPE = #studentType and
ACTIVE = 'P';
END IF;
END;
If you are using ANSI SQL PL syntax, then your procedure would look something like this below.
Notice that variables and parameters should not begin with the # character, unlike other RDBMS.
Using a naming convention , like p_ to indicate a parameter, or v_ to indicate a variable is just optional noise, but some people like it.
CREATE or replace PROCEDURE My_StrProc
( IN p_rollNumber Varchar(18),
IN p_studentType Varchar(3),
OUT p_studentID Varchar(15),
OUT p_oldStudentType Varchar(4) ,
OUT p_oldBranch Varchar(3) ,
OUT p_newStudentType Varchar(4) ,
OUT p_newBranch Varchar(4)
)
BEGIN
IF p_studentType IS NOT NULL
THEN
Select
REGISTRATION_NO,
OLD_STUD_TYPE,
OLD_BRANCH,
NEW_STUD_TYPE,
NEW_BRANCH
into
p_studentID
,p_oldStudentType
,p_oldBranch
,p_newStudentType
,p_newBranch
From
Migrated_Student
Where
OLD_STUDENT_NUM = p_rollNumber
and ACTIVE = 'P';
ELSE
Select
REGISTRATION_NO,
OLD_STUD_TYPE,
OLD_BRANCH,
NEW_STUD_TYPE,
NEW_BRANCH
into
p_studentID
,p_oldStudentType
,p_oldBranch
,p_newStudentType
,p_newBranch
From
Migrated_Student
Where
OLD_STUDENT_NUM = p_rollNumber and
OLD_STUD_TYPE = p_studentType and
ACTIVE = 'P';
END IF;
END

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.

Doing validation in stored procedure if data already exist

I want to create a stored procedure where I want to check if I add a Bin no and if exist in the table it should give me validation message otherwise it should work
I tried like below but it is not working
ALTER PROCEDURE [dbo].[sp_P_WMS_Stock_Adj_Val_Proc]
(#Bin_no nvarchar(max))
AS BEGIN
IF (#Bin_no = )
BEGIN
RAISERROR('Bin no already exist', 16, 1)
RETURN
END
ELSE
BEGIN
SELECT DISTINCT
Location_Name + '-' + convert(varchar, mkey)
FROM
WMS_Storage_Bin
WHERE
status = 'Confirmed'
AND location_name = #Bin_no
END
END
I am using SQL Server 2005.
If you really must do this in a stored procedure - then use this:
ALTER PROCEDURE dbo.ValidateWMSStock
(#Bin_no nvarchar(max))
AS BEGIN
IF EXISTS (SELECT * FROM dbo.WMS_Storage_Bin
WHERE location_name = #Bin_no)
BEGIN
RAISERROR('Bin no already exist', 16, 1)
RETURN
END
ELSE
BEGIN
SELECT DISTINCT
Location_Name + '-' + convert(varchar, mkey)
FROM
WMS_Storage_Bin
WHERE
status = 'Confirmed'
AND location_name = #Bin_no
END
END
But as Mitch Wheat already said - it's probably much easier to just put a unique constraint on that column:
ALTER TABLE dbo.WMS_Storage_Bin
ADD CONSTRAINT UQ_Location_Name UNIQUE(location_name)
Once the unique constraint is in place, if you attempt to insert a row with a location_name that already exists, you'll get an error
Msg 2627, Level 14, State 1, Line xx
Violation of UNIQUE KEY constraint 'UQ_Location_Name'. Cannot insert duplicate key in object 'dbo.WMS_Storage_Bin'. The duplicate key value is (......).
Update:
I tried this - I believe the code I provided works just fine:
DECLARE #BinTable TABLE (ID INT NOT NULL, Location_Name NVARCHAR(100))
INSERT INTO #BinTable VALUES(1, N'A1112'), (2, N'A1113'), (3, N'A1114'), (4, N'A1121')
DECLARE #Bin_No NVARCHAR(MAX)
-- SET #Bin_No = N'A1112' -- this prints "Bin already exists" as expected
SET #Bin_No = N'A4112' -- this prints "Bin does *NOT* exist" as expected
IF EXISTS (SELECT * FROM #BinTable WHERE location_name = #Bin_no)
PRINT 'Bin already exists'
ELSE
PRINT 'Bin does *NOT* exist'

SQL Filter condition with value or Null

In the below procedure i may pass #Type value only sometimes otherwise it will be NULL.
How can i handle querying all data when NULL is passed and specific records when i pass a type. I don't want to build dynamic query for this simple handling.
CREATE PROCEDURE [dbo].[GetPatientImages]
(
#TenantId BIGINT,
#PatientId BIGINT,
#Type NVARCHAR(100)
)
AS
BEGIN
SET NOCOUNT ON
IF #TenantId IS NULL
RAISERROR('The value for #TenantID should not be null', 15, 1) -- with log
ELSE
BEGIN
SELECT
P.[DisplayFileName],
P.[StoredFileName],
P.[Location],
P.[Type],
P.[Description]
FROM
PatientImage P
WHERE P.PatientId=#PatientId AND P.TenantId=#TenantId AND P.[Type]=#Type
ORDER BY P.[Type] DESC
END
END
Try this:
WHERE P.PatientId=#PatientId AND P.TenantId=#TenantId AND
(#Type is null or P.[Type]=#Type)

Stored Procedure that accepts all table fields and updates those values

I'm working through a couple practice questions and I've run across this problem, I keep getting an error when trying to execute the procedure that says
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Procedure'."
Can someone please help?
Write a procedure UpdateTitle that accepts all the Title table columns and will update the title with those values. Raise error messages for the following: The ISBN does not exist The Category and/or Publisher Codes are not valid.
Create PROCEDURE UpdateTitle (#ISBN char(10), #SuggestedPrice smallmoney,#NumberInStock smallint,#PublisherCode int,#CategoryCode int)
AS
BEGIN
IF #ISBN is null or #CategoryCode is null or #PublisherCode is null
BEGIN
RAISERROR ('ISBN,CategoryCode, or PublisherCode is not valid please enter valid data',16,1)
END
ELSE
BEGIN
IF (SELECT COUNT(*) FROM Title WHERE ISBN = #ISBN) = 0
BEGIN
RAISERROR ('ISBN does not exist.',16,1)
END
ELSE
BEGIN
SELECT 'Table Sucessfully Updated.';
UPDATE Title
SET SuggestedPrice = #SuggestedPrice
WHERE ISBN = #ISBN;
BEGIN
IF (SELECT COUNT(*) FROM Title WHERE ISBN = #ISBN) = 0
BEGIN
RAISERROR ('ISBN does not exist.',16,1)
END
ELSE
BEGIN
SELECT 'Table Sucessfully Updated.';
UPDATE Title
SET NumberInStock = #NumberInStock
WHERE ISBN = #ISBN;
END
BEGIN
IF (SELECT COUNT(*) FROM Title WHERE ISBN = #ISBN) = 0
BEGIN
RAISERROR ('ISBN does not exist.',16,1)
END
ELSE
BEGIN
SELECT 'Table Sucessfully Updated.';
UPDATE Title
SET PublisherCode = #PublisherCode
WHERE ISBN = #ISBN;
END
BEGIN
IF (SELECT COUNT(*) FROM Title WHERE ISBN = #ISBN) = 0
BEGIN
RAISERROR ('ISBN does not exist.',16,1)
END
ELSE
BEGIN
SELECT 'Table Sucessfully Updated.';
UPDATE Title
SET CategoryCode = #CategoryCode
WHERE ISBN = #ISBN;
END
END
END
END
END
END
END
GO
Then
Execute Procedure UpdateTitle #ISBN ='1021031040', #suggestedproce ='40' , #NumberInStock ='10', #PublisherCode = '200', #CategoryCode = '1'
Execute Procedure UpdateTitle ...
Should be:
EXEC dbo.UpdateTitle ...
Some other comments:
ISBN is no longer limited to 10 characters (this change happened in 2007, if you believe WikiPedia).
Always use the schema prefix when creating or referencing objects.
You only need to check that the ISBN is valid once. And you shouldn't do so using a count IMHO, especially since - presumably - that is the key and it could only ever return 0 or 1 anyway.
You shouldn't select "update successful" and then perform the update. You should make sure the update was successful before telling the user it was successful.
There is no reason to separate this out into multiple updates either.
Please be liberal with carriage returns, indenting and whitespace. The value in readability is worth the extra cost in typing it (since you only type it once, but you will read it multiple times).
Use RETURN; as an exit mechanism so that you don't have to nest IF and ELSE multiple times.
Always use SET NOCOUNT ON; at the beginning of your procedures.
You probably want to customize the message to tell the user which parameter(s) were invalid.
Oh yeah, and please future-proof your code by using semi-colons to terminate statements.
Here is a much more concise version that satisfies all of your requirements:
CREATE PROCEDURE dbo.UpdateTitle
#ISBN CHAR(10),
#SuggestedPrice SMALLMONEY,
#NumberInStock SMALLINT,
#PublisherCode INT,
#CategoryCode INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #msg VARCHAR(255);
IF #ISBN IS NULL OR #CategoryCode IS NULL OR #PublisherCode IS NULL
BEGIN
SELECT #msg = 'The following parameter(s) were invalid:'
+ CASE WHEN #ISBN IS NULL THEN ' #ISBN' ELSE '' END
+ CASE WHEN #CategoryCode IS NULL THEN ' #CategoryCode' ELSE '' END
+ CASE WHEN #PublisherCode IS NULL THEN ' #PublisherCode' ELSE '' END;
RAISERROR (#msg, 11, 1);
RETURN;
END
IF NOT EXISTS (SELECT 1 FROM dbo.Title WHERE ISBN = #ISBN)
BEGIN
SET #msg = 'ISBN %s does not exist.';
RAISERROR(#msg, 11, 1, #ISBN);
RETURN;
END
BEGIN TRY
UPDATE dbo.Title
SET SuggestedPrice = #SuggestedPrice,
NumberInStock = #NumberInStock,
PublisherCode = #PublisherCode,
CategoryCode = #CategoryCode
WHERE ISBN = #ISBN;
SELECT 'Update successful.';
END TRY
BEGIN CATCH
SET #msg = ERROR_MESSAGE();
RAISERROR(#msg, 11, 1);
END CATCH
END
GO