assisatnce in the sql function - sql

I have posted below written code earlier and got the correct code with the removal of errors, but my criteria is not satisfying, below is the raw data im passing as the paramater
2007:10113:/I/69071/MLI/Eldridge
and in return the output should be "69071", for this i have given the below function but im not gettig the output,a nd i have kept some other condition to satisfy other requirements also, please help me.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON --2007:10113:/I/69071/MLI/Eldridge
go
ALTER FUNCTION [dbo].[Empnum] (#RAWDATA NVARCHAR(300))
RETURNS VARCHAR(30)
AS
BEGIN
DECLARE #TEMP1 NVARCHAR(300), #EMPNUM NVARCHAR(10), #TEMP2 NVARCHAR(300), #TEMP3 NVARCHAR(300)
SET #TEMP3 = 'Disabled'
SET #EMPNUM=''
SET #TEMP2 = #RAWDATA
IF( CHARINDEX(#TEMP3,#RAWDATA,1) = 0)
BEGIN
-- SET #EMPNUM='11'
IF ISNUMERIC(SUBSTRING(#RAWDATA,1,1)) = 1
BEGIN
--
IF((LEN(#RAWDATA) - LEN(REPLACE(#TEMP2,'/','')))>1)
BEGIN
SET #RAWDATA=SUBSTRING(#RAWDATA,CHARINDEX('/',#RAWDATA)+1,LEN(#RAWDATA))
SET #RAWDATA=SUBSTRING(#RAWDATA,CHARINDEX('/',#RAWDATA)+1,LEN(#RAWDATA))
SET #RAWDATA=SUBSTRING(#RAWDATA,1,CHARINDEX('/',#RAWDATA)-1)
IF( CHARINDEX('*C',#RAWDATA) = 0 OR
CHARINDEX('CV',#RAWDATA) = 0 OR
CHARINDEX('AV',#RAWDATA) = 0 OR
CHARINDEX('LV',#RAWDATA) = 0 )
BEGIN
SET #EMPNUM = ''
RETURN #EMPNUM
END
ELSE
BEGIN
IF ISNUMERIC(SUBSTRING(#RAWDATA,1,1)) = 1
BEGIN
SET #EMPNUM = #RAWDATA
RETURN #EMPNUM
END
ELSE
IF((SUBSTRING(#RAWDATA,1,1)='C') AND ISNUMERIC(SUBSTRING(#RAWDATA,2,1)) = 1)
BEGIN
SET #EMPNUM = SUBSTRING(#RAWDATA,2,LEN(#RAWDATA))
RETURN #EMPNUM
END
END
END
END
END
RETURN #EMPNUM
END

I have found the error in my code, and changed the "="o "<>"
IF( CHARINDEX('*C',#RAWDATA) <> 0 OR
CHARINDEX('CV',#RAWDATA) <> 0 OR
CHARINDEX('AV',#RAWDATA) <> 0 OR
CHARINDEX('LV',#RAWDATA) <> 0 )
BEGIN
SET #EMPNUM = ''
RETURN #EMPNUM
END

Related

if else change declared variable in database SQL

I don't know how to change the value of already declared variable.
I want to update something in my table base on the declared variable.
what I've tried so far
IF NOT EXISTS
(SELECT 1 FROM [DB_databaseOne].[dbo].[data_tblOne]
WHERE orderBy= 'AC038234'
and prodCode = 'P0008'
and batchID = '1'
and is_buy = 3 and voidFlag is null)
BEGIN
DECLARE #MSG VARCHAR(300) = 'GOOD'
END
ELSE
BEGIN
DECLARE #MSG VARCHAR(300) = 'NOT GOOD'
END
You should DECLARE your variable only once. You can have multiple SET statements to assign a value:
DECLARE #MSG VARCHAR(300)
IF NOT EXISTS
(SELECT 1 FROM [DB_databaseOne].[dbo].[data_tblOne]
WHERE orderBy= 'AC038234'
and prodCode = 'P0008'
and batchID = '1'
and is_buy = 3 and voidFlag is null)
BEGIN
SET #MSG = 'GOOD'
PRINT #MSG
END
ELSE
BEGIN
SET #MSG = 'NOT GOOD'
PRINT #MSG
END

SQL Server stored procedure: finding the values of Odd and even

I'm using #subno as Input. And I had to find the odd and even numbers. 16 is not a fix and it can be any other number. My question is how to find the odd and even number of my input?
Lastly, subno includes ( . ) dot at any position. e.g 123456.789123 I need to find the odd and even number of "123456" and the odd and even number of "789123" the dot ( . ) is the separator.
Once you find the odd for the left side, sum them up together. Once you find the even number for left side sum it up as well and then add the total odd to the total even values. That goes the same for the right side eg "789123".
Please help me. this is my 2nd week of trying to find the solution. Once you find all the total values for each side, multiply them together. example "123456" - total value of odd and even * the "789123" total value of odd and even.
It is for the the check digit validation. Validating the subscriber number. after validating through the calculation it should match the calculated reference number to the valid check digit number. It's the business rule. Kind of algorithm
create procedure ProcedureName
(#subno VARCHAR(16), --Input the 16 subscriber number
#result INT OUT,
)
as
begin
IF(LEN(#subno) <> 16)
SET #result = 1 -- INVALID RESULT
ELSE
IF(#subno % 2 = 0)
SET #result = #subno - even numbers
ELSE
SET #result = #subno --odd numbers
end
Please see below my sample work
-- this is the sample
create procedure ProcedureName
(
#subno VARCHAR(20), --Subscriber no
#result INT OUT, --result is invalid for 1, valid for 0
#payamt int
)
as
DECLARE #WA VARCHAR(2)
DECLARE #Weights varchar(9)
DECLARE #I INT
DECLARE #WD INT
DECLARE #WP INT
DECLARE #A INT
DECLARE #B INT
DECLARE #R INT
DECLARE #WR INT
SET #WR = 0
SET #R = 0
SET #A = 0
SET #B = 0
SET #WP = 0
SET #I = 0
BEGIN
IF (LEN(#subNo) = 7) AND (SUBSTRING(#subno,1,1) = '2') OR (SUBSTRING(#subno,1,1) = '9')
BEGIN
SET #result = 0 --VALID
END
ELSE IF(LEN(#subno) = 8) AND (SUBSTRING(#subno,1,1) = '2') OR
(SUBSTRING(#subno,1,1) = '9')
BEGIN
SET #result = 0 --VALID
END
ELSE IF(LEN(#subno) = 9)
BEGIN
SET #WA = SUBSTRING(#subno,1,2)
IF(#WA = '65')
set #result = 1 -- INVALID
else
BEGIN
SET #Weights = '12121212'
SET #WA = SUBSTRING(#subno,9,1)
SET #WD = 0
SET #I = 1
WHILE #I<9
BEGIN
SET #WP = cast(SUBSTRING(#Weights, #I,1)as int) * cast(SUBSTRING(#subno, #I, 1) as int)
IF(#WP > 9)
BEGIN
SET #A = SUBSTRING(CAST(#WP AS VARCHAR),1,1)
SET #B = SUBSTRING(CAST(#WP AS VARCHAR),2,1)
SET #WP = CAST(#A AS INT) + CAST(#B AS INT)
END
SET #WD = #WP + #WD
SET #I = #I + 1
END
SET #R = #WD % 10
IF(#R <> 0)
SET #WR = 10 - #R
ELSE
SET #WR = #R
IF(#WR <> CAST(#WA AS INT))
BEGIN
SET #result = 1 -- INVALID
END
ELSE
BEGIN
SET #result = 0 -- VALID
END
END
END
ELSE IF (LEN(#subno) = 10)
BEGIN
SET #I =1
SET #WD = 0
SET #Weights = '121212121'
SET #WA = SUBSTRING(#subno,10,1)
WHILE(#I < 10)
BEGIN
SET #WP = CAST(SUBSTRING(#Weights, #I, 1)AS INT) * CAST(SUBSTRING(#subno, #I, 1) AS INT)
IF(#WP > 9)
BEGIN
SET #A = SUBSTRING(CAST(#WP AS VARCHAR),1,1)
SET #B = SUBSTRING(CAST(#WP AS VARCHAR),2,1)
SET #WP = CAST(#A AS INT) + CAST(#B AS INT)
END
SET #WD = #WP + #WD
SET #I = #I + 1
END
SET #R = #WD % 10
IF(#R <> 0)
SET #WR = 10 - #R
ELSE
SET #WR = #R
IF (#WR<> #WA)
BEGIN
SET #result = 1 -- INVALID
END
ELSE
BEGIN
SET #result = 0 -- VALID
END
END
ELSE
SET #result = 1 -- INVALID
END
Split the values which u get . Then iterate iver each side and add them. Please see the sample below.
declare #v varchar (16) , #num1 varchar(20) , #num2 varchar(20)
set #v = '1234567.78906656'
select #num1 = substring(#v,0,charindex('.',#v))
select #num2 = substring(#v,charindex('.',#v)+1,len(#v))
--select #num1 = convert(int, substring(#v,0,charindex('.',#v)))
--select #num2 = substring(#v,charindex('.',#v)+1,len(#v))
declare #index int = 1 ,#len INT , #char CHAR
declare #TotalOddL int = 0
declare #TotalEvenL int = 0
DECLARE #FullTotL INT = 0
declare #TotalOddR int = 0
declare #TotalEvenR int = 0
DECLARE #FullTotR INT = 0
DECLARE #TEMP INT
set #len= LEN(#num1)
WHILE #index <= #len
BEGIN
set #char = SUBSTRING(#num1, #index, 1)
SET #TEMP = cast(#char as int)
IF(#TEMP % 2 = 0)
SET #TotalEvenL = #TotalEvenL + #char
else
SET #TotalOddL = #TotalOddL + #char
SET #FullTotL = #TotalEvenL + #TotalOddL
SET #index= #index+ 1
END
Select 'LeftSide total' , #FullTotL
Select 'Left Side odd' , #TotalOddL
Select 'Left Side Even' , #TotalEvenL
SET #index = 1
set #len= LEN(#num2)
WHILE #index <= #len
BEGIN
set #char = SUBSTRING(#num2, #index, 1)
SET #TEMP = cast(#char as int)
IF(#TEMP % 2 = 0)
SET #TotalEvenR= #TotalEvenR + #char
else
SET #TotalOddR = #TotalOddR + #char
SET #FullTotR = #TotalEvenR + #TotalOddR
SET #index= #index+ 1
END
select 'TotalRSide' , #FullTotR
select 'RsideOdd' , #TotalOddR
select 'RSideEven' , #TotalEvenR
select 'Multiplied value' , #FullTotR * #FullTotL
create or replace procedure prc_even_odd(i_number in number, o_result out varchar2)
as
begin
if (mod(i_number,2) = 0) then
o_result := 'EVEN';
else
o_result := 'ODD';
end prc_even;

stored procedure exists details not validate

Im create the stored procedure , I want to check UserCategoryCode and UserCategoryName, existing record, im make a existing record , but not a correctly working it for the UserCategoryCode, how can i do it? im try to do it, but not work, (Its work for the UserCategoryName )
SP
ALTER PROCEDURE [dbo].[UserCategories_InsertUpdate]
#UserCategoryId int,
#UserCategoryCode varchar(50),
#UserCategoryName varchar(250),
#Remarks nvarchar(max),
#StatusId int,
-- #StatusChangeDate DATETIME,
#CreateId int,
#Mode varchar(50),
#iOutput int output
AS
BEGIN
BEGIN TRY
BEGIN TRAN
IF #Mode = 'Add'
BEGIN
IF NOT EXISTS (SELECT UserCategoryCode,UserCategoryName FROM UserCategories WHERE UserCategoryCode = #UserCategoryCode AND UserCategoryName = #UserCategoryName)
BEGIN
INSERT INTO UserCategories(
UserCategoryCode,
UserCategoryName,
StatusId,
StatusChangeDate,
CreateBy,
CreatedDate,
Remarks
)
VALUES(
#UserCategoryCode,
#UserCategoryName,
#StatusId,GETDATE(),
#CreateId,GETDATE(),
#Remarks
)
SET #iOutput = 1 --save successful--
END
ELSE
BEGIN
SET #iOutput=-3 --existing record--
END
END
ELSE IF #Mode = 'Modify'
BEGIN
UPDATE UserCategories
SET UserCategoryCode = #UserCategoryCode,
UserCategoryName = #UserCategoryName,
StatusId = #StatusId,
Remarks = #Remarks,
EditBy = #CreateId,
EditDate = GETDATE()
WHERE UserCategoryId = #UserCategoryId
SET #iOutput = 2 --save successful--
END
COMMIT
END TRY
BEGIN CATCH
print ERROR_MESSAGE()
SET #iOutput = -2 --sp error--
ROLLBACK
END CATCH
END
oh finally its working , i found the solution ,
IF NOT EXISTS (SELECT UserCategoryCode FROM UserCategories WHERE UserCategoryCode = #UserCategoryCode)
IF NOT EXISTS (SELECT UserCategoryName FROM UserCategories WHERE UserCategoryName = #UserCategoryName)
BEGIN
INSERT INTO UserCategories(
UserCategoryCode,
UserCategoryName,
StatusId,
StatusChangeDate,
CreateBy,
CreatedDate,
Remarks
)
VALUES(
#UserCategoryCode,
#UserCategoryName,
#StatusId,GETDATE(),
#CreateId,GETDATE(),
#Remarks
)
SET #iOutput = 1 --save successful--
END
ELSE
BEGIN
SET #iOutput=-3 --existing record--
END
ELSE
BEGIN
SET #iOutput=-5 --existing record--
END
END
ELSE IF #Mode = 'Modify'
BEGIN
UPDATE UserCategories
SET UserCategoryCode = #UserCategoryCode,
UserCategoryName = #UserCategoryName,
StatusId = #StatusId,
Remarks = #Remarks,
EditBy = #CreateId,
EditDate = GETDATE()
WHERE UserCategoryId = #UserCategoryId
SET #iOutput = 2 --save successful--
END
COMMIT
END TRY
BEGIN CATCH
print ERROR_MESSAGE()
SET #iOutput = -2 --sp error--
ROLLBACK
END CATCH
END
and code behind
else if (output == -3)
{
lblMsg.Text = "Already Exists!";
lblMsg.ForeColor = System.Drawing.Color.Orange;
}
else if (output == -5)
{
lblMsg.Text = "Already Exists!";
lblMsg.ForeColor = System.Drawing.Color.Orange;
}

Uniqueidentifier as parameter in SQL Server Function

I have created a Function in SQL Server 2012 that I will use in a Check Constraint on a table.
The function works as expected if I do:
SELECT [dbo].[CheckValidCardnumberForShellTankingen] ('700678036658047691' ,'2925CA00-6DD5-4F9D-AB0E-AA15DBBD388B')
But when I try to set the expression in Check Constraint so:
([dbo].[CheckValidCardnumberForShellTankingen]([Volledig kaartnummer],[RollBackCode])=(1))
I get a Messaage: "Error validating constraint 'CK_MyConstraint'"
I use the Uniqueidentifier in a Where clause and the strange thing is if I replace the parameter with string containing the Uniqueidentifier I dont get this error.
Here is the Function:
-- =============================================
-- Author: Anders Pedersen
-- Create date: 2015-02-13
-- Description: Check of the Cardnumber of a transaction is valid.
-- =============================================
CREATE FUNCTION [dbo].[CheckValidCardnumberForShellTankingen]
(
-- Add the parameters for the function here
#Cardnumber NvarChar(50),
#RollBackCode NvarChar(200)
)
RETURNS BIT
AS
BEGIN
-- Declare the return variable here
DECLARE
#Result BIT
,#ResultLenght BIT
,#ResultPrefix BIT
,#CardLenght INT
,#SupplierID INT
,#UseCardnumber BIT
,#Prefix NvarChar(50)
-- Add the T-SQL statements to compute the return value here
SET #Result = 0
SET #ResultLenght = 0
SET #ResultPrefix = 0
SET #CardLenght = -1
SET #SupplierID = -1
SET #UseCardnumber = 0
SET #Prefix = ''
-- Get the UseCardnumber and the SupplierID
SELECT #UseCardnumber = C.UseCardNumber, #SupplierID = F.SupplierID
FROM Client C INNER JOIN
ClientFileUploads F ON C.ClientID = F.ClientID
WHERE F.RollBackCode = #RollBackCode
--WHERE F.RollBackCode = '2925CA00-6DD5-4F9D-AB0E-AA15DBBD388B'
-- Only carry out the check if the Client use Cards else set the check to True (1)
IF #UseCardnumber = 1
BEGIN
SELECT #CardLenght = [CardNumberLenght], #Prefix = ISNULL([Prefix],'') FROM [dbo].[Supplier] AS S WHERE S.SupplierID = #SupplierID
IF (#CardLenght IS NULL) OR (#CardLenght = 0)
BEGIN
SET #ResultLenght = 1
END
ELSE
BEGIN
IF (LEN(#Cardnumber) - #CardLenght)= 0
BEGIN
SET #ResultLenght = 1
END
ELSE
BEGIN
SET #ResultLenght = 0
END
END
IF SUBSTRING(#Cardnumber, 1, LEN(#Prefix)) = #Prefix
BEGIN
SET #ResultPrefix = 1
END
ELSE
BEGIN
SET #ResultPrefix = 0
END
IF ((#ResultLenght = 1) AND (#ResultPrefix = 1))
BEGIN
SET #Result = 1
END
ELSE
BEGIN
SET #Result = 0
END
END
ELSE
BEGIN
SET #Result = 1
END
-- Return the result of the function
RETURN #Result
END
GO
If #RollBackCode is a uniqueidentifier, I recommend making the parameter a uniqueidentifier and not a varchar.
As Rhys Jones points out, you shouldn't use a UDF in a check constraint.
See
https://dba.stackexchange.com/questions/22297/udf-in-check-constraint-downside
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/078b720f-faac-425c-b51a-33bcecb263d2/check-constraint-with-udf-problem-with-lots-of-data?forum=transactsql
http://sqlblog.com/blogs/tibor_karaszi/archive/2009/12/17/be-careful-with-constraints-calling-udfs.aspx
If you need to check in a trigger and roll back -- SQL Server - After Insert/ For Insert - Rollback

An object or column name is missing or empty

I am getting the following error
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name.
for the query show below:
CREATE PROC [dbo].[Sp_Table1] #ctlg_ipt_event_id int
AS
SET NOCOUNT ON
DECLARE #current_status NCHAR(1), #ready_status_code NCHAR(1)
DECLARE #current_action NCHAR(1), #ready_action_code NCHAR(1), #done_action_code NCHAR(1)
DECLARE #pst_user_id int
SELECT #current_status = status_code
,#current_action = action_code
,#pst_user_id = last_mod_user_id
FROM merch_ctlg_ipt_event
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
Select #ready_status_code = 'o'
, #ready_action_code = 'a'
, #done_action_code = 'b'
IF #current_status <> #ready_status_code OR #current_action <> #ready_action_code
BEGIN
RETURN
END
BEGIN TRAN
declare #rows int
,#err int
,#i int
,#name nvarchar(50) --COLLATE SQL_AltDiction_Pref_CP850_CI_AS
,#resolved_View_Name_category_id int
,#xref_value int
,#availability_start_date datetime
,#availability_end_date datetime
,#status_code int
,#last_mod_user_id int
,#CT datetime
,#supplier_id int
,#View_Name_id int
select #i = 1
,#CT = current_timestamp
Select Distinct mc.name,
mc.resolved_View_Name_category_id,
mc.xref_value,
mc.availability_start_date,
mc.availability_end_date,
mc.status_code,
CASE WHEN mc.last_mod_user_id = 42
THEN #pst_user_id
ELSE mc.last_mod_user_id
END as last_mod_user_id,
CURRENT_tsp
,IDENTITY(int,1,1) as rn
,si.supplier_id
,si.View_Name_id
into #temp
FROM View_Name AS si
JOIN merch_ctlg_ipt_View_Name AS mc
ON mc.supplier_id = si.supplier_id
AND mc.resolved_View_Name_id = si.View_Name_id
AND mc.cat_imp_event_id = #ctlg_ipt_event_id
AND mc.accept_flag = 'y'
WHERE si.shipper_flag = 'n'
select #rows=##ROWCOUNT,#err=##error
if #rows > 0 and #err=0
Begin
While #i <=#rows
begin
SElect #name = name,
#resolved_View_Name_category_id = resolved_View_Name_category_id,
#xref_value = xref_value,
#availability_start_date = availability_start_date,
#availability_end_date = availability_end_date,
#status_code = mc.status_code,
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
,#supplier_id=supplier_id
,#View_Name_id=View_Name_id
from #temp
Where rn=#i
UPDATE View_Name
SET name = #name,
View_Name_category_id = #resolved_View_Name_category_id,
xref_value = #xref_value,
availability_start_date = #availability_start_date,
availability_end_date = #availability_end_date,
status_code = #status_code,
last_mod_user_id = #last_mod_user_id ,
last_mod_timestamp = #CT
Where #sup_id = supplier_id
AND #View_Name_id = View_Name_id
AND shipper_flag = 'n'
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
End
End
UPDATE
merch_ctlg_ipt_event
SET action_code = #done_action_code,
last_mod_timestamp = #CT
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
COMMIT TRAN
Return
go
Could you please help ?
You have 2 commas in a row here
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
Also probably not relevant to the error message but you have a line
Where #sup_id = supplier_id
but the declared variable is #supplier_id