Making SQL statement efficient and easy to understand - sql

I have problem that I have to make my code shorter .
code:
IF #result_var = #expected_value
BEGIN
INSERT INTO reports.consistencycheckhistory VALUES
(
Getdate(),
#rule_guid,
'Ok',
#result_var
)
IF CONVERT(DATE,#check_time) <> CONVERT(DATE, Sysdatetime())
BEGIN
UPDATE reports.consistencycheckrules
SET ok_days_count =#ok_days_count + 1 ,
last_check_time=#check_time
where rule_guid=#rule_guid
END
END
ELSE
BEGIN
INSERT INTO reports.consistencycheckhistory VALUES
(
Getdate(),
#rule_guid,
'Error',
#result_var
)
UPDATE reports.consistencycheckrules
SET ok_days_count=0,
last_check_time=#check_time
WHERE rule_guid=#rule_guid
END
There have to be only 1 insert and 1 update that is what my boss is saying but I don't know if it is possible.

IF #result_var = #expected_value
BEGIN
SET #Status = 'Ok'
END
ELSE
BEGIN
SET #Status = 'Error'
END
IF CONVERT(DATE,#check_time) <> CONVERT(DATE, Sysdatetime())
BEGIN
SET #ok_days_count = #ok_days_count + 1;
END
ELSE
BEGIN
SET #ok_days_count = 0;
END
INSERT INTO reports.consistencycheckhistory VALUES
(
Getdate(),
#rule_guid,
#Status,
#result_var
)
UPDATE reports.consistencycheckrules
SET ok_days_count = #ok_days_count ,
last_check_time=#check_time
where rule_guid=#rule_guid

You could use case statements within insert and within update. Not that it would make it much easier to understand, but would fulfill your boss' wish.

Try this (might need a bit of tweaking):
INSERT INTO reports.consistencycheckhistory
VALUES
(
Getdate(),
#rule_guid,
CASE
WHEN #result_var = #expected_value
then 'Ok'
ELSE 'Error"
END,
#result_var
)
UPDATE reports.consistencycheckrules
SET
ok_days_count =#ok_days_count +
CASE
WHEN CONVERT(DATE,#check_time) <> CONVERT(DATE,Sysdatetime())
then 1
ELSE
0
END,
last_check_time=#check_time
where rule_guid=#rule_guid

In the query there is case where you do not have to update columns, i.e. #result_var = #expected_value and CONVERT(DATE,#check_time) = CONVERT(DATE, Sysdatetime())
DECLARE #Should_Update bit
SET #Should_Update=0
IF #result_var = #expected_value
BEGIN
SET #Status = 'Ok'
END
ELSE
BEGIN
SET #Status = 'Error'
END
IF(#result_var = #expected_value)
BEGIN
IF CONVERT(DATE,#check_time) <> CONVERT(DATE, Sysdatetime())
BEGIN
SET #Should_Update=1
SET #ok_days_count = #ok_days_count + 1;
END
END
ELSE
BEGIN
SET #Should_Update=1
SET #ok_days_count = 0;
END
INSERT INTO reports.consistencycheckhistory VALUES
(
Getdate(),
#rule_guid,
#Status,
#result_var
)
UPDATE reports.consistencycheckrules
SET ok_days_count = #ok_days_count ,
last_check_time=#check_time
where rule_guid=#rule_guid AND #Should_Update=1

IF #result_var = #expected_value
BEGIN
SET #Status = 'Ok'
END
ELSE
BEGIN
SET #Status = 'Error'
END
IF #Status = 'Ok'
BEGIN
IF CONVERT(DATE, #check_time) <> CONVERT(DATE, Sysdatetime())
BEGIN
SET #ok_days_count = #ok_days_count + 1;
END
ELSE
BEGIN
#ok_days_count=#ok_days_count
END
end
ELSE
BEGIN
SET #ok_days_count = 0;
end
INSERT INTO reports.consistencycheckhistory VALUES
(
Getdate(),
#rule_guid,
#Status,
#result_var
)
UPDATE reports.consistencycheckrules
SET ok_days_count = #ok_days_count,
last_check_time = #check_time
WHERE rule_guid = #rule_guid
This seems like the right answer

Related

Incorrect Syntax near 0

Im getting this error message I've tried to look at my code I cant seem to see where its coming from, please help.
ERROR:-
Msg 102, Level 15, State 1, Procedure _TESTbspPostAPTrans, Line 249
Incorrect syntax near '0'.
SET ANSI_NULLS ON
GO
CREATE procedure [dbo].[_TESTbspPostAPTrans]
#AutoIdx bigint = NULL OUTPUT,
#TxDate datetime,
#Id varchar(5),
#AccountLink int,
#TrCodeID int,
#Debit float,
#Credit float,
#CurrencyID int,
#ExchangeRate float,
#ForeignDebit float,
#ForeignCredit float,
#Description varchar(100),
#TaxTypeID int,
#Reference varchar(50),
#Order_No varchar(50),
#ExtOrderNum varchar(50),
#AuditNumber varchar(50),
#Tax_Amount float,
#ForeignTaxAmount float,
#Project int,
#Outstanding float,
#ForeignOutstanding float,
#InvNumKey bigint,
#UserName varchar(20),
#Reference2 varchar(50),
#SettlementTermsID int,
#TxBranchID int,
#GLTaxAccountID int = 0,
#cLineUserFields varchar (max) = ''
as
set nocount on
set identity_insert PostAP on
if (IsNull(#AccountLink, 0) = 0) begin
RAISERROR('_bspPostAPTrans: No Accounts Payable Account specified!', 16, 1)
return 0
end
else
if (IsNull(#Id, '') = '') begin
RAISERROR('_bspPostAPTrans: No Transaction ID specified!', 16, 1)
return 0
end
else
if (IsNull(#TrCodeID, 0) = 0) begin
RAISERROR('_bspPostAPTrans: No Transaction Code specified!', 16, 1)
return 0
end
else
if (IsNull(#AuditNumber, '') = '') begin
RAISERROR('_bspPostAPTrans: No Audit Trail Number specified!', 16, 1)
return 0
end
--begin tran --CC: Will now be controlled in Code
declare #SPError int
declare #BranchID int
select #BranchID = Vendor_iBranchID from Vendor where DCLink = #AccountLink
if isnull(#AutoIdx, 0) <= 0 begin
if isnull (#AccountLink, 0) = 4917 begin
set nocount on
set identity_insert PostAR on
--begin tran --CC: Will now be controlled in Code
select #BranchID = Client_iBranchID from Client where DCLink = #AccountLink
select #AutoIdx = ident_current('PostAR') + 1
insert into PostAR
(
AutoIdx,
TxDate,
[Id],
AccountLink,
TrCodeID,
Debit,
Credit,
iCurrencyID,
fExchangeRate,
fForeignDebit,
fForeignCredit,
[Description],
TaxTypeID,
Reference,
Order_No,
ExtOrderNum,
cAuditNumber,
Tax_Amount,
fForeignTax,
Project,
Outstanding,
fForeignOutstanding,
InvNumKey,
UserName,
cReference2,
iPostSettlementTermsID,
iTxBranchID,
iGLTaxAccountID
)
values
(
#AutoIdx,
#TxDate,
#Id,
#AccountLink,
#TrCodeID,
#Debit,
#Credit,
#CurrencyID,
#ExchangeRate,
#ForeignDebit,
#ForeignCredit,
#Description,
#TaxTypeID,
#Reference,
#Order_No,
#ExtOrderNum,
#AuditNumber,
#Tax_Amount,
#ForeignTaxAmount,
#Project,
#Outstanding,
#ForeignOutstanding,
#InvNumKey,
#UserName,
#Reference2,
#SettlementTermsID,
#TxBranchID,
#GLTaxAccountID
)
set #SPError = ##ERROR
set identity_insert PostAR off
-- Post User Defined Fields
if (len (#cLineUserFields) > 0) begin
declare #UDFSQLText1 varchar(max)
set #UDFSQLText1 = 'update PostAR set ' + #cLineUserFields + ' where AutoIdx = ' + CAST(#AutoIdx as varchar)
execute (#UDFSQLText1)
set #SPError = ##ERROR
if #SPError <> 0 goto AbortTran
-- Update Client Balances
end
UPDATE dbo.Client
SET DCBalance = Round(IsNull (DCBalance, 0) + (#Debit - #Credit), 4),
fForeignBalance = Round(IsNull(fForeignBalance, 0) + (#ForeignDebit - #ForeignCredit), 4)
WHERE DCLink = #AccountLink
set #SPError = ##ERROR
if #SPError <> 0 goto AbortTran1
goto CommitTran1
--rollback tran --CC: Will now be controlled in Code
RAISERROR (#SPError, 16, 1)
return #SPError
if #SPError <> 0 goto AbortTran
END
select #AutoIdx = ident_current('PostAP') + 1
insert into PostAP
(
AutoIdx,
TxDate,
[Id],
AccountLink,
TrCodeID,
Debit,
Credit,
iCurrencyID,
fExchangeRate,
fForeignDebit,
fForeignCredit,
[Description],
TaxTypeID,
Reference,
Order_No,
ExtOrderNum,
cAuditNumber,
Tax_Amount,
fForeignTax,
Project,
Outstanding,
fForeignOutstanding,
InvNumKey,
DTStamp,
UserName,
cReference2,
iPostSettlementTermsID,
PostAP_iBranchID,
iTxBranchID,
iGLTaxAccountID
)
values
(
#AutoIdx,
#TxDate,
#Id,
#AccountLink,
#TrCodeID,
#Debit,
#Credit,
#CurrencyID,
#ExchangeRate,
#ForeignDebit,
#ForeignCredit,
#Description,
#TaxTypeID,
#Reference,
#Order_No,
#ExtOrderNum,
#AuditNumber,
#Tax_Amount,
#ForeignTaxAmount,
#Project,
#Outstanding,
#ForeignOutstanding,
#InvNumKey,
GetDate(),
#UserName,
#Reference2,
#SettlementTermsID,
#BranchID,
#TxBranchID,
#GLTaxAccountID
)
set #SPError = ##ERROR
set identity_insert PostAP off
if #SPError <> 0 goto AbortTran1
-- Post User Defined Fields
if (len (#cLineUserFields) > 0) begin
declare #UDFSQLText varchar(max)
set #UDFSQLText = 'update PostAP set ' + #cLineUserFields + ' where AutoIdx = ' + CAST(#AutoIdx as varchar)
execute (#UDFSQLText)
set #SPError = ##ERROR
if #SPError <> 0 goto AbortTran1
end
-- Update Vendor Balances
UPDATE VENDOR
SET DCBalance = Round(IsNull (DCBalance, 0) + (#Credit - #Debit), 4),
fForeignBalance = Round(IsNull(fForeignBalance, 0) + (#ForeignCredit - #ForeignDebit), 4)
WHERE DCLink = #AccountLink
set #SPError = ##ERROR
if #SPError <> 0 goto AbortTran1
goto CommitTran1
AbortTran1:
--rollback tran --CC: Will now be controlled in Code
RAISERROR (#SPError, 16, 1)
return #SPError
CommitTran1:
--commit tran --CC: Will now be controlled in Code
return 0 --scope_identity() -- return can only return an int, not a bigint,
-- AutoIdx has been added as a paramater for the BA sync and is an OUTPUT paramter
GO
Any help will be greatly appreciated
I think in line 62 and 63 you have 2 opened BEGIN with just first END in line 159.on END is missing in line 160

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;
}

Stored procedure update specific column by parameter

I am developing a stored procedure to update specific columns using parameters.
For example:
CREATE PROCEDURE save_proc
(
#userid varchar(5),
#column varchar(10),
#data varchar(50)
)
AS
BEGIN
UPDATE MyProfile
SET #column = #data
WHERE userid = #userid
The following is my code that I've tried but didn't work. Is it possible to do such an update by updating specific columns through parameters? Thanks
You can build up a query in your stored procedure and execute.
CREATE PROCEDURE save_proc
(
#userid varchar(5),
#column varchar(10),
#data varchar(50)
)
AS
BEGIN
exec sp_executesql N'UPDATE MyProfile SET ' + #column + '=''' + #data + ''' WHERE userid = ''' + #userid + ''''
END
The method may lead to security concern however.
Its doable but i would avoid doing it.... you code should be like below:
DECLARE #column varchar(10)
DECLARE #data varchar(50)
UPDATE DummyTable
SET
col1 = CASE WHEN #column = 'Col1' THEN #data ELSE col1 END ,
col2 = CASE WHEN #column = 'Col2' THEN #data ELSE col2 END
where userid = #userid
.
.
.
Hope that this is what you are looking for
Using a CASE statement causes all columns identified to once again be updated; this would invoke a reindexing for some indexes upon columns wherein that change, even if the same value, occurs. Waste of execution updates on server.
An IF statement is best option for single value, especially if value is NOT the same type as the column datatype.
IF(#fieldName IS NULL) SELECT #fieldName = ''
IF(#updateValue IS NULL) SELECT #updateValue = ''
DECLARE #myCount int
SELECT #myCount = count(*) FROM [dbo].[myTable] WHERE #inventoryID = #updateInventoryID
--if no valid data to update, return -1 for noUpdate
IF(0 = #updateInventoryID
OR 0 = #myCount
OR '' = #fieldName
OR '' = #updateValue)
RETURN -1
BEGIN TRAN
IF('notes' = #fieldName)
UPDATE [dbo].[myTable]
SET [notes] = #updateValue, [modifyDate] = GETDATE()
WHERE [inventoryID] = #updateInventoryID
IF('reorderPoint' = #fieldName)
BEGIN
SET #newValueInt = CONVERT(int, #updateValue)
UPDATE [dbo].[myTable]
SET [reorderPoint] = #newValueInt, [modifyDate] = GETDATE()
WHERE [inventoryID] = #updateInventoryID
END
IF('safetyStock' = #fieldName)
BEGIN
SET #newValueInt = CONVERT(int, #updateValue)
UPDATE [dbo].[myTable]
SET [safetyStock] = #newValueInt, [modifyDate] = GETDATE()
WHERE [inventoryID] = #updateInventoryID
END
IF('quantityOnHand' = #fieldName)
BEGIN
SET #newValueInt = CONVERT(int, #updateValue)
UPDATE [dbo].[myTable]
SET [quantityOnHand] = #newValueInt, [modifyDate] = GETDATE()
WHERE [inventoryID] = #updateInventoryID
END
IF('totalLeadTimeDays' = #fieldName)
BEGIN
SET #newValueInt = CONVERT(int, #updateValue)
UPDATE [dbo].[myTable]
SET [totalLeadTimeDays] = #newValueInt, [modifyDate] = GETDATE()
WHERE [inventoryID] = #updateInventoryID
END
IF('stockTakeETADate' = #fieldName)
BEGIN
SET #newValueDatetime = CONVERT(datetime, #updateValue)
UPDATE [dbo].[myTable]
SET [stockTakeETADate] = #newValueDatetime, [modifyDate] = GETDATE()
WHERE [inventoryID] = #updateInventoryID
END
COMMIT
A Try/Catch is advisable

Getting Request Timeout sometimes from only one SP?

I have a lot of stored procedures. But I am only getting Request Timeout sometimes only for this SP ?
ALTER PROCEDURE [dbo].[Insertorupdatedevicecatalog]
(#OS NVARCHAR(50)
,#UniqueID VARCHAR(500)
,#Longitude FLOAT
,#Latitude FLOAT
,#Culture VARCHAR(10)
,#Other NVARCHAR(200)
,#IPAddress VARCHAR(50)
,#NativeDeviceID VARCHAR(50))
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TranCount INT;
SET #TranCount = ##TRANCOUNT;
DECLARE #OldUniqueID VARCHAR(500) = ''-1'';
SELECT #OldUniqueID = [UniqueID] FROM DeviceCatalog WHERE (#NativeDeviceID != '''' AND [NativeDeviceID] = #NativeDeviceID);
BEGIN TRY
IF #TranCount = 0
BEGIN TRANSACTION
ELSE
SAVE TRANSACTION Insertorupdatedevicecatalog;
DECLARE #Geo GEOGRAPHY = geography::STGeomFromText(''POINT('' + CONVERT(VARCHAR(100), #Longitude) + '' '' + CONVERT(VARCHAR(100), #Latitude) + '')'', 4326);
IF EXISTS(SELECT 1 FROM DeviceCatalog WHERE [UniqueID] = #UniqueID)
BEGIN
DECLARE #OldGeo GEOGRAPHY
,#OldCity NVARCHAR(100)
,#OldCountry NVARCHAR(100)
,#OldAddress NVARCHAR(100);
SELECT #OldGeo = [LastUpdatedLocationFromJob]
,#OldCity = [City]
,#OldCountry = [Country]
,#OldAddress = [Address]
FROM DeviceCatalog
WHERE [UniqueID] = #UniqueID;
UPDATE DeviceCatalog
SET [OS] = #OS
,[Location] = #Geo
,[Culture] = #Culture
,[Other] = #Other
,[IPAddress] = #IPAddress
WHERE [UniqueID] = #UniqueID;
IF (#OldGeo IS NULL OR #OldAddress IS NULL OR #OldCity IS NULL OR #OldCountry IS NULL OR ISNULL(#Geo.STDistance(#OldGeo) / 1000,0) > 50)
BEGIN
UPDATE DeviceCatalog
SET [Lastmodifieddate] = Getdate()
WHERE [UniqueID] = #UniqueID;
END
END
ELSE
BEGIN
INSERT INTO DeviceCatalog
([OS]
,[UniqueID]
,[Location]
,[Culture]
,[Other]
,[IPAddress]
,[NativeDeviceID])
VALUES (#OS
,#UniqueID
,#Geo
,#Culture
,#Other
,#IPAddress
,#NativeDeviceID);
IF(#OldUniqueID != ''-1'' AND #OldUniqueID != #UniqueID)
BEGIN
EXEC DeleteOldAndroidDeviceID #OldUniqueID, #UniqueID;
END
END
LBEXIT:
IF #TranCount = 0
COMMIT;
END TRY
BEGIN CATCH
DECLARE #Error INT, #Message VARCHAR(4000), #XState INT;
SELECT #Error = ERROR_NUMBER() ,#Message = ERROR_MESSAGE() ,#XState = XACT_STATE();
IF #XState = -1
ROLLBACK;
IF #XState = 1 AND #TranCount = 0
rollback
IF #XState = 1 AND #TranCount > 0
ROLLBACK TRANSACTION Insertorupdatedevicecatalog;
RAISERROR (''Insertorupdatedevicecatalog: %d: %s'', 16, 1, #error, #message) ;
END CATCH
END
The timeout occurs due to two updates to same table inside same transaction. You could avoid it with a case statement. Also whole IF ELSE can be replaced with a merge.
MERGE INTO DeviceCatalog DC
USING (SELECT #UniqueID AS UniqueID) T ON (DC.UniqueID = T.UniqueID)
WHEN MATCHED THEN
UPDATE SET [OS] = #OS
,[Location] = #Geo
,[Culture] = #Culture
,[Other] = #Other
,[IPAddress] = #IPAddress
,[Lastmodifieddate] = (CASE
WHEN (LastUpdatedLocationFromJob IS NULL OR [Address] IS NULL OR [City] IS NULL OR [Country] IS NULL OR ISNULL(#Geo.STDistance(LastUpdatedLocationFromJob) / 1000,0) > 50)
THEN Getdate()
ELSE [Lastmodifieddate]
END)
WHEN NOT MATCHED THEN
INSERT INTO DeviceCatalog
([OS]
,[UniqueID]
,[Location]
,[Culture]
,[Other]
,[IPAddress]
,[NativeDeviceID])
VALUES (#OS
,#UniqueID
,#Geo
,#Culture
,#Other
,#IPAddress
,#NativeDeviceID)
WHEN NOT MATCHED BY SOURCE AND #OldUniqueID != ''-1'' AND #OldUniqueID != #UniqueID THEN
DELETE;
Try it and check whether this is what you expected.
Already discussed here
You can achieve it using sp_getapplock in TSQL.
But you need a wrapper storedproc or batch for this. Check the following example it will help you to desing your wrapper sp/batch statement.
Sample Code Snippet
Create table MyTable
(
RowId int identity(1,1),
HitStartedAt datetime,
HitTimestamp datetime,
UserName varchar(100)
)
Go
Create proc LegacyProc (#user varchar(100), #CalledTime datetime)
as
Begin
Insert Into MyTable
Values(#CalledTime, getdate(), #user);
--To wait for 10 sec : not required for your procedures, producing the latency to check the concurrent users action
WAITFOR DELAY '000:00:10'
End
Go
Create Proc MyProc
(
#user varchar(100)
)
as
Begin
Declare #PorcName as NVarchar(1000), #CalledTime datetime
Begin Tran
--To get the Current SP Name, it should be unique for each SP / each batch
SET #PorcName = object_name(##ProcID)
SET #CalledTime = Getdate()
--Lock the Current Proc
Exec sp_getapplock #Resource = #PorcName, #LockMode = 'Exclusive'
--Execute Your Legacy Procedures
Exec LegacyProc #user, #CalledTime
--Release the lock
Exec sp_releaseapplock #Resource = #PorcName
Commit Tran
End
You are doing two seperate updates on the DeviceCatalog table where [UniqueID] = #UniqueID in the same transaction.
I bet your locking/request timeout issue is happening when:
IF (#OldGeo IS NULL OR #OldAddress IS NULL OR #OldCity IS NULL OR #OldCountry IS NULL OR ISNULL(#Geo.STDistance(#OldGeo) / 1000,0) > 50) is true.
Try something like this in place of the two updates.
Obviously test in dev first.
In the else clause, you want to have it insert something if the when is false. Here I am just inserting the current before update field contents.
UPDATE DeviceCatalog
SET [OS] = #OS
,[Location] = #Geo
,[Culture] = #Culture
,[Other] = #Other
,[IPAddress] = #IPAddress
,[Lastmodifieddate] =
case when (
#OldGeo is NULL
OR
#OldAddress is NULL
OR
#OldCity is NULL
OR
#OldCountry is NULL
OR
ISNULL(#Geo.STDistance(#OldGeo) / 1000,0) > 50
) then Getdate()
else [Lastmodifieddate]
end
WHERE [UniqueID] = #UniqueID

assisatnce in the sql function

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