Generation Sequence CertificateNo - sql-server

I have block code for generation for CertificateNo. I need anyone check performance my block code
--Struct table config
--drop table CertificateSequenceGen;
CREATE TABLE [dbo].[CertificateSequenceGen](
[Bus] [varchar](15) NULL,
[MonthNo] [varchar](4) NOT NULL,
[DateStart] [date] NULL,
[DateEnd] [date] NULL,
[SequenceStart] [int] NOT NULL,
[SequenceEnd] [int] NOT NULL,
[CurrentNo] [int] NOT NULL
) ON [PRIMARY]
---initial default data into table
INSERT INTO [dbo].[CertificateSequenceGen]([Bus],[MonthNo],[DateStart],[DateEnd],[SequenceStart],[SequenceEnd],[CurrentNo])
VALUES('ABC','1902','2019-02-01','2019-03-01',1,9999999,1);
--Store for generate certificateN
--drop PROC prdGetCertificateNo
create PROC prdGetCertificateNo
#Bus varchar(15) = '',
#Prefix varchar(15) = '',
#CertificateNo varchar(31) OUTPUT
as
begin
update
CertificateSequenceGen
set
#CertificateNo = #Prefix + Bus + MonthNo + left (REPLICATE('0',7 - len(CurrentNo)) + cast (CurrentNo as varchar(7)),7),
CurrentNo = CurrentNo + 1
where
Bus = #Bus and GETDATE() between DateStart and DateEnd;
end
/*
--execute procedure genarate the CertificateNo
declare #Prefix varchar(15) = 'YZ', #ProductCode varchar(15) = 'ABC', #CertificateNo varchar(31);
exec [dbo].[prdGetCertificateNo] #ProductCode, #Prefix, #CertificateNo output
select #CertificateNo;
*/
after exec procedure below is result
--result---
YZABC19020000001

Related

Executing a stored procedure by picking SQL variable from a list in T-SQL without using Cursor

I have a list of values, and i need the variable to pick it up one by one and execute the commands below. I need to achieve something like below in T-SQL. Is it possible without cursors?
SET NOCOUNT ON;
DECLARE #IPA VARCHAR(10)
FOR #IPA IN ['ADV, 'AC','AHA','ALPEB','AG','APCWEB]
IF OBJECT_ID('[ESProcess].[dbo].[EJ_Test]') IS NOT NULL
DROP TABLE [ESProcess].[dbo].[EJ_Test]
CREATE TABLE [ESProcess].[dbo].[EJ_Test]
(
[PRIM] [varchar](50) NULL,
[CLAIM_ID] [varchar](100) NULL,
[P_CLAIMNO] [varchar](100) NULL,
[Pro] [varchar](3) NULL,
[VALUE] [varchar](50) NULL,
[ErrorCode] [int] NULL,
[DESCRIP] [varchar](500) NULL,
[FILENAME] [varchar](300) NULL
)
INSERT INTO [ESProcess].[dbo].[EJ_Test]
SELECT
PRIM,a.CLAIM_ID,P_CLAIMNO, Pro, u.VALUE,
NULL AS ErrorCode, NULL AS DESCRIP, [FILENAME]
FROM
[SPID].[#IPA].[dbo].837_in_1 a
JOIN
[SPID].[#IPA].[dbo].[837_In_U] u ON a.ED_ID = u.M_ID
WHERE
a.CREATEDATE >= '20221001'
AND u.FNO = '20'
AND Pro = 'D'
END
Here. Note that drop-creating the table means that at the end you will only have data from APCWEB.
SET NOCOUNT ON;
DECLARE #IPA VARCHAR(10)
declare #sql nvarchar(max)
create table #ipas
(
ord int
,ipa varchar(10)
)
insert #ipas(ord,ipa) values
(1,'ADV')
,(2,'AC')
,(3,'AHA')
,(4,'ALPEB')
,(5,'AG')
,(6,'APCWEB')
declare ipa_cursor cursor local fast_forward for
select ipa from #ipas order by ord
open ipa_cursor
while 1=1
begin
fetch next from ipa_cursor into #IPA
if ##fetch_status<>0 break
set #sql=N''+
'IF OBJECT_ID(''[ESProcess].[dbo].[EJ_Test]'') IS NOT NULL
DROP TABLE [ESProcess].[dbo].[EJ_Test]
CREATE TABLE [ESProcess].[dbo].[EJ_Test]
(
[PRIM] [varchar](50) NULL,
[CLAIM_ID] [varchar](100) NULL,
[P_CLAIMNO] [varchar](100) NULL,
[Pro] [varchar](3) NULL,
[VALUE] [varchar](50) NULL,
[ErrorCode] [int] NULL,
[DESCRIP] [varchar](500) NULL,
[FILENAME] [varchar](300) NULL
)
INSERT INTO [ESProcess].[dbo].[EJ_Test]
SELECT
PRIM,a.CLAIM_ID,P_CLAIMNO, Pro, u.VALUE,
NULL AS ErrorCode, NULL AS DESCRIP, [FILENAME]
FROM
[SPID].'+quotename(#IPA)+'.[dbo].837_in_1 a
JOIN
[SPID].'+quotename(#IPA)+'.[dbo].[837_In_U] u ON a.ED_ID = u.M_ID
WHERE
a.CREATEDATE >= ''20221001''
AND u.FNO = ''20''
AND Pro = ''D'''
exec sp_executesql #sql
end -- cursor while
close ipa_cursor
deallocate ipa_cursor

SQL Server Always Encrypted Operand type clash: varchar is incompatible with varchar(60) when running EXEC sproc

I am unable to EXEC a stored procedure that upserts a table that has an encrypted column using Always Encrypted. However, I am able to copy the SQL from the sproc and run that as regular SQL with the parameters set, Just cannot get the sproc to fire when executing the sproc via the EXEC function in SSMS which is also causing problems in the application
The table has a trigger on it that inserts into another audit table of similar structure that is also encrypted using the same encryption. I have done the usual thing:
Checking the Enable Parameterizaion for Always Encrypted in Query Options Setting column encryption setting=enabled on the Connection Settings.
Refreshing the encyrption metadata for the sproc:
EXEC sp_refresh_parameter_encryption 'organization.uspOrganizationAddressUpsert'
Tables:
CREATE TABLE [organization].[OrganizationAddress](
[OrganizationAddressId] [int] IDENTITY(1,1) NOT NULL,
[CreatedUser] [int] NOT NULL,
[CreatedDate] [datetime2](7) NOT NULL,
[LastUpdateUser] [int] NOT NULL,
[LastUpdateDate] [datetime2](7) NOT NULL,
[RemovedDate] [datetime2](7) NULL,
[Address1] [varchar](60) NOT NULL,
[Address2] [varchar](60) NULL,
[City] [varchar](60) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[State] [varchar](60) NOT NULL,
[ZipCode] [varchar](60) NOT NULL,
[ClientNumberId] [int] NOT NULL
CREATE TABLE [audit].[OrganizationAddressAudit](
[OrganizationAddressId] [int] NOT NULL,
[CreatedUser] [int] NOT NULL,
[CreatedDate] [datetime2](7) NOT NULL,
[LastUpdateUser] [int] NOT NULL,
[LastUpdateDate] [datetime2](7) NOT NULL,
[RemovedDate] [datetime2](7) NULL,
[Address1] [varchar](60) NOT NULL,
[Address2] [varchar](60) NULL,
[City] [varchar](60) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[State] [varchar](60) NOT NULL,
[ZipCode] [varchar](60) NOT NULL,
[ClientNumberId] [int] NOT NULL,
[OperationDate] [datetime] NOT NULL,
[Operation] [varchar](50) NOT NULL,
[OperationBy] [varchar](100) NOT NULL
Stored Procedure:
ALTER PROCEDURE [organization].[uspOrganizationAddressUpsert]
#OrganizationId INT,
#ExecutingUserId INT,
#Address1 VARCHAR(60),
#Address2 VARCHAR(60),
#City VARCHAR(60),
#State VARCHAR(60),
#ZipCode VARCHAR(60),
#ClientNumberId INT
AS
BEGIN
SET NOCOUNT ON
DECLARE #RightNow AS DATETIME2 = SYSDATETIME()
If EXISTS (Select 1 From [organization].[OrganizationAddress] Where ClientNumberId = #ClientNumberId)
BEGIN
UPDATE [organization].[OrganizationAddress] SET
LastUpdateUser = #ExecutingUserId,
LastUpdateDate = #RightNow,
Address1 = #Address1,
Address2 = #Address2,
City = #City,
[State] = #State,
ZipCode = #ZipCode,
RemovedDate = Null
Where ClientNumberId = #ClientNumberId
END
ELSE
BEGIN -- INSERT part of the UPSERT
INSERT INTO [organization].[OrganizationAddress]
(CreatedUser
,CreatedDate
,LastUpdateUser
,LastUpdateDate
,Address1
,Address2
,City
,[State]
,ZipCode
,ClientNumberId)
VALUES
(#ExecutingUserId
,#RightNow
,#ExecutingUserId
,#RightNow
,#Address1
,#Address2
,#City
,#State
,#ZipCode
,#ClientNumberId)
END
END
Running the stored procedure code with the paramteers set is fine, but I am unable to EXEC the sproc:
declare #orgId INT = 1;
declare #client int = 888;
declare #user int = 1;
declare #Add1 varchar(60)= 'Test Address1';
declare #Add2 varchar(60)= 'Test Address2';
declare #city varchar(60) = 'City';
declare #state varchar(60) = 'St';
declare #zip varchar(60) = '12345';
EXEC organization.uspOrganizationAddressUpsert
#OrganizationID=#orgID,
#ExecutingUserId = #user, -- int
#Address1 = #Add1, -- varchar(60)
#Address2 = #Add2, -- varchar(60)
#City = #city, -- varchar(60)
#State = #state, -- varchar(60)
#ZipCode = #zip, -- varchar(60)
#ClientNumberId = #client; -- int
Msg 206, Level 16, State 2, Procedure uspOrganizationAddressUpsert, Line 0 [Batch Start Line 1]
Operand type clash: varchar is incompatible with varchar(60) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'BankruptcyApp') collation_name = 'SQL_Latin1_General_CP1_CI_AS'
I created a similar table in a test DB with VARCHAR(60) for the enrcrypted columns, a trigger, and an audit table and its working fine there and I cant find any differences in the table/sproc/trigger that would allow it to work there and not here. I've pretty much exhausted the other posts and blogs I can find.
Fixed! Needed to update the app code to specify the data type and length:
parameters.Add("#City", organizationAddress.City, System.Data.DbType.AnsiString, System.Data.ParameterDirection.Input, 60);
where it was previously just:
parameters.Add("#City", organizationAddress.City)
This at least get the app to run the sproc but still cant run it from SSMS via EXEC

stored procedure inserting values in wrong columns

I am facing a strange problem,
My c# program is inserting values into database(basically checks if the record exists then updates it, otherwise, inserts into the table)
the query for the stored procedure as well as table is shown below:
Table
CREATE TABLE [dbo].[PurchaseReceiptbySheetOil](
[id] [int] IDENTITY(1,1) NOT NULL,
[LPOId] [int] NULL,
[POLineNumber] [nvarchar](100) NULL,
[Serial] [nvarchar](100) NULL,
[DateLoaded] [date] NULL,
[truck] [nvarchar](100) NULL,
[Trailer] [nvarchar](100) NULL,
[Transporter] [nvarchar](100) NULL,
[Driver] [nvarchar](max) NULL,
[PassportNumber] [nvarchar](100) NULL,
[ObserverdVolume] [nvarchar](100) NULL,
[Terminal] [nvarchar](100) NULL,
[Tank] [nvarchar](100) NULL,
[TempInTank] [nvarchar](100) NULL,
[VCF20] [float] NULL,
[VolumeLTS20C] [float] NULL,
[Density20C] [float] NULL,
[WeightMTons] [float] NULL,
[Destination] [nvarchar](max) NULL,
[BottomSEALNRS] [nvarchar](max) NULL,
[TopSealNRS] [nvarchar](100) NULL,
[SAMPLESEALNRS] [nvarchar](max) NULL,
[PhysicalDipsOnTheTruckinMM1] [int] NULL,
[PhysicalDipsOnTheTruckinMM2] [int] NULL,
[PhysicalDipsOnTheTruckinMM3] [int] NULL,
[PhysicalDipsOnTheTruckinMM4] [int] NULL,
[PhysicalDipsOnTheTruckinMM5] [int] NULL,
[PhysicalDipsOnTheTruckinMM6] [int] NULL,
[Site] [nvarchar](100) NULL,
[LineNumber] [int] NULL,
[CreatedOn] [datetime] NULL,
[UpdatedOn] [datetime] NULL,
[CreatedBy] [nvarchar](100) NULL,
[UpdatedBy] [nvarchar](100) NULL
)
Stored Procedure
CREATE PROCEDURE [dbo].[CreateUpdatePurchaseReceiptbySheetOil]
#Site nvarchar(100),
#CreatedOn datetime,
#UpdatedOn datetime,
#CreatedBy nvarchar(100),
#UpdatedBy nVarchar(100),
#DateLoaded date,
#truck nvarchar(100),
#Trailer nvarchar(100),
#Transporter nvarchar(100),
#Driver nvarchar(max),
#PassportNumber nvarchar(100),
#ObserverdVolume nvarchar(100),
#Terminal nvarchar(100),
#Tank nvarchar(100),
#TempInTank nvarchar(100),
#VCF20 float,
#VolumeLTS20C float,
#Density20C float,
#WeightMTons float,
#Destination nvarchar(max),
#BottomSEALNRS nvarchar(max),
#SAMPLESEALNRS nvarchar(max),
#PhysicalDipsOnTheTruckinMM1 int,
#PhysicalDipsOnTheTruckinMM2 int,
#PhysicalDipsOnTheTruckinMM3 int,
#PhysicalDipsOnTheTruckinMM4 int,
#PhysicalDipsOnTheTruckinMM5 int,
#PhysicalDipsOnTheTruckinMM6 int,
#Serial Nvarchar(100),
#LineNumber int,
#POLineNumber int,
#TopSealNRS nvarchar(100),
#LPOId nvarchar(100)
AS
BEGIN
if exists(select * from [PurchaseReceiptbySheetOil] where Site= #Site and
Serial=#Serial and LineNumber = #LineNumber)
BEGIN
UPDATE [dbo].[PurchaseReceiptbySheetOil]
SET [DateLoaded] = #DateLoaded,
UpdatedOn =#UpdatedOn,
UpdatedBy=#UpdatedBy,
[truck] = #truck
,[Trailer] = #Trailer
,[Transporter] = #Transporter
,[Driver] = #Driver
,[PassportNumber] = #PassportNumber
,[ObserverdVolume] = #ObserverdVolume
,[Terminal] = #Terminal
,[Tank] = #Tank
,[TempInTank] = #TempInTank
,[VCF20] = #VCF20
,[VolumeLTS20C] = #VolumeLTS20C
,[Density20C] = #Density20C
,[WeightMTons] = #WeightMTons
,[Destination] = #Destination
,[BottomSEALNRS] = #BottomSEALNRS
,[SAMPLESEALNRS] = #SAMPLESEALNRS
,[PhysicalDipsOnTheTruckinMM1] = #PhysicalDipsOnTheTruckinMM1
,[PhysicalDipsOnTheTruckinMM2] = #PhysicalDipsOnTheTruckinMM2
,[PhysicalDipsOnTheTruckinMM3] = #PhysicalDipsOnTheTruckinMM3
,[PhysicalDipsOnTheTruckinMM4] = #PhysicalDipsOnTheTruckinMM4
,[PhysicalDipsOnTheTruckinMM5] = #PhysicalDipsOnTheTruckinMM5
,[PhysicalDipsOnTheTruckinMM6] = #PhysicalDipsOnTheTruckinMM6
,[Serial] = #Serial
,TopSealNRS=#TopSealNRS
,LPOId=#LPOId
WHERE Site= #Site and Serial=#Serial and LineNumber = #LineNumber
END
else
BEGIN
INSERT INTO [dbo].[PurchaseReceiptbySheetOil]
([LPOId]
,[POLineNumber]
,[Serial]
,[DateLoaded]
,[truck]
,[Trailer]
,[Transporter]
,[Driver]
,[PassportNumber]
,[ObserverdVolume]
,[Terminal]
,[Tank]
,[TempInTank]
,[VCF20]
,[VolumeLTS20C]
,[Density20C]
,[WeightMTons]
,[Destination]
,[BottomSEALNRS]
,[TopSealNRS]
,[SAMPLESEALNRS]
,[PhysicalDipsOnTheTruckinMM1]
,[PhysicalDipsOnTheTruckinMM2]
,[PhysicalDipsOnTheTruckinMM3]
,[PhysicalDipsOnTheTruckinMM4]
,[PhysicalDipsOnTheTruckinMM5]
,[PhysicalDipsOnTheTruckinMM6]
,[Site]
,[LineNumber]
,[CreatedOn]
,[UpdatedOn]
,[CreatedBy]
,[UpdatedBy])
VALUES
(#LPOId,#POLineNumber,
#Serial,#DateLoaded,
#truck,#Trailer,#Transporter,#Driver,
#PassportNumber,#ObserverdVolume,#Terminal,#Tank,#TempInTank,
#VCF20,#VolumeLTS20C,#Density20C,#WeightMTons,#Destination,#BottomSEALNRS,
#TopSealNRS,#SAMPLESEALNRS,
#PhysicalDipsOnTheTruckinMM1,#PhysicalDipsOnTheTruckinMM2,
#PhysicalDipsOnTheTruckinMM3,#PhysicalDipsOnTheTruckinMM4,
#PhysicalDipsOnTheTruckinMM5,#PhysicalDipsOnTheTruckinMM6,#Site,
#LineNumber,#CreatedOn,#UpdatedOn,#CreatedBy,#UpdatedBy)
END
END
Now when i run the following query to execute stored procedure:
exec sp_executesql N'EXECUTE [dbo].[CreateUpdatePurchaseReceiptbySheetOil]
#Site ,#CreatedOn ,
#UpdatedOn ,#CreatedBy
,#UpdatedBy ,#DateLoaded ,#truck
,#Trailer ,#Transporter ,#Driver
,#PassportNumber ,#ObserverdVolume
,#Terminal ,#Tank ,#TempInTank ,#VCF20
,#VolumeLTS20C ,#Density20C ,#WeightMTons
,#Destination ,#BottomSEALNRS,#TopSealNRS
,#SAMPLESEALNRS ,#PhysicalDipsOnTheTruckinMM1
,#PhysicalDipsOnTheTruckinMM2 ,#PhysicalDipsOnTheTruckinMM3
,#PhysicalDipsOnTheTruckinMM4 ,#PhysicalDipsOnTheTruckinMM5
,#PhysicalDipsOnTheTruckinMM6 ,#Serial ,#LineNumber
,#POLineNumber,#LPOId',N'#CreatedBy nvarchar(7),#CreatedOn datetime,
#UpdatedBY nvarchar(7),#UpdatedOn datetime,#Site nvarchar(7),
#DateLoaded nvarchar(9),#truck nvarchar(7),#Trailer nvarchar(7),
#Transporter nvarchar(5),#Driver nvarchar(8),#PassportNumber nvarchar(8),
#ObserverdVolume nvarchar(6),#Terminal nvarchar(5),#Tank
nvarchar(3),#TempInTank nvarchar(4),
#VCF20 nvarchar(6),#VolumeLTS20C nvarchar(6),#Density20C
nvarchar(6),#WeightMTons nvarchar(6),
#Destination nvarchar(5),#BottomSEALNRS nvarchar(14),#TopSealNRS
nvarchar(33),#SAMPLESEALNRS nvarchar(7),
#PhysicalDipsOnTheTruckinMM1 nvarchar(4),#PhysicalDipsOnTheTruckinMM2
nvarchar(4),#PhysicalDipsOnTheTruckinMM3 nvarchar(4),
#PhysicalDipsOnTheTruckinMM4 nvarchar(4),#PhysicalDipsOnTheTruckinMM5
nvarchar(4),#PhysicalDipsOnTheTruckinMM6 nvarchar(4),
#Serial nvarchar(5),#LineNumber int,#POLineNumber int,#LPOId int',
#CreatedBy=N'Tanveer',
#CreatedOn='2017-05-08 11:50:24.283',
#UpdatedBY=N'Tanveer',
#UpdatedOn='2017-05-08 11:50:24.283',
#Site=N'Site001',
#DateLoaded=N'20-Apr-17',
#truck='',
#Trailer='',
#Transporter=N'00002',
#Driver='',
#PassportNumber=''
#ObserverdVolume=N'40.000',
#Terminal=N'TOTAL',
#Tank=N'223',#TempInTank=N'30.0',#VCF20=N'0.9915',#VolumeLTS20C=N'39.660',
#Density20C=N'0.8219',
#WeightMTons=N'32.597',#Destination=N' DRC ',#BottomSEALNRS=N' 02697558/559
',#TopSealNRS=N' 02697560 TO 562+02697564 TO 566 ',
#SAMPLESEALNRS=N'781845 '
,#PhysicalDipsOnTheTruckinMM1=N'1472',#PhysicalDipsOnTheTruckinMM2=N'1592',
#PhysicalDipsOnTheTruckinMM3=N'1706',#PhysicalDipsOnTheTruckinMM4=N'1832',
#PhysicalDipsOnTheTruckinMM5=N'1808',
#PhysicalDipsOnTheTruckinMM6=N'1362',#Serial=N'00001',#LineNumber=8,
#POLineNumber=0,#LPOId=7
the values for the columns get swapped during the insert, Note the value for serial is 0001 but it will insert as 1362 instead of 0001 and for some other columns also the values will change(not all).
Please note that I have checked the sequence of columns in insert and
values sections. I am specifying columns but still facing this issue.
I have dropped and created the table again.
During debugging in sql
server, the value is correct when debugging starts i.e.0001 but then
changes, i don\t know why.
The sequence of parameters in Stored procedure definition should be the same when we are executing it, I was assuming it is not depending on the sequence but the parameter name and i was wrong.

Converting a working script into Stored procedure

Posted this question yesterday and got a solution as well. The solution script works fine as-is but when I converted it into a stored procedure it gives wrong results. Not able to identify where exactly I am messing up with the code.
Table Schema:
CREATE TABLE [dbo].[VMaster](
[VID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[VName] [varchar](30) NOT NULL
)
GO
CREATE TABLE [dbo].[TblMaster](
[SID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[VID] [int] NOT NULL,
[CreatedDate] [datetime] default (getdate()) NOT NULL,
[CharToAdd] [varchar](10) NOT NULL,
[Start] [int] NOT NULL,
[End] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TblDetails](
[DetailsID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[SID] [int] NOT NULL,
[Sno] [int] NOT NULL,
[ConcatenatedText] [varchar](20) NOT NULL,
[isIssued] [bit] default (0) NOT NULL,
[isUsed] [bit] default (0) NOT NULL
)
GO
ALTER TABLE [dbo].[TblMaster] WITH CHECK ADD CONSTRAINT [fk_SI_id] FOREIGN KEY([VID])
REFERENCES [dbo].[VMaster] ([VID])
GO
ALTER TABLE [dbo].[TblMaster] CHECK CONSTRAINT [fk_SI_id]
GO
Working solution:
CREATE FUNCTION [dbo].[udf-Create-Range-Number] (#R1 money,#R2 money,#Incr money)
-- Syntax Select * from [dbo].[udf-Create-Range-Number](0,100,2)
Returns
#ReturnVal Table (RetVal money)
As
Begin
With NumbTable as (
Select NumbFrom = #R1
union all
Select nf.NumbFrom + #Incr
From NumbTable nf
Where nf.NumbFrom < #R2
)
Insert into #ReturnVal(RetVal)
Select NumbFrom from NumbTable Option (maxrecursion 32767)
Return
End
Declare #Table table (SID int,VID int,CreateDate DateTime,CharToAdd varchar(25),Start int, [End] Int)
Insert Into #Table values
(1,1,'2016-06-30 19:56:14.560','ABC',1,5),
(2,1,'2016-06-30 19:56:14.560','XYZ',10,20),
(3,2,'2016-06-30 19:56:14.560','P1',10,15)
Declare #Min int,#Max int
Select #Min=min(Start),#Max=max([End]) From #Table
Select B.SID
,Sno = A.RetVal
,ConcetratedText = concat(B.CharToAdd,A.RetVal)
From (Select RetVal=Cast(RetVal as int) from [dbo].[udf-Create-Range-Number](#Min,#Max,1)) A
Join #Table B on A.RetVal Between B.Start and B.[End]
Order By B.Sid,A.RetVal
Stored procedure (This generates more records than the working solution!!)
CREATE PROCEDURE [dbo].[Add_Details]
(
#VID INT,
#CreatedDate DATETIME,
#CharToAdd VARCHAR(10),
#Start INT,
#End INT
)
AS
SET NOCOUNT ON
BEGIN
DECLARE #SID INT
INSERT INTO [dbo].[TblMaster] (VID, CreatedDate, CharToAdd, Start, [End])
VALUES (#VID, #CreatedDate, #CharToAdd, #Start, #End)
SET #SID = SCOPE_IDENTITY()
DECLARE #Min INT, #Max INT
SELECT #Min = #Start, #Max = #End
INSERT INTO [dbo].[TblDetails] (SID, Sno, [ConcatenatedText])
SELECT #SID
,Sno = A.RetVal
,ConcatenatedText = CONCAT(B.CharToAdd,A.RetVal)
FROM (SELECT RetVal = CAST(RetVal AS INT) FROM [dbo].[udf-Create-Range-Number](#Min,#Max,1)) A
JOIN dbo.TblMaster B ON A.RetVal BETWEEN B.Start AND B.[End]
ORDER BY B.SID,A.RetVal
END
GO
Declare #tmp datetime
Set #tmp = getdate()
EXEC [dbo].[Add_Details]
#VID = 1,
#CreatedDate = #tmp,
#CharToAdd = 'ABC',
#Start = 1,
#End = 5
EXEC [dbo].[Add_Details]
#VID = 1,
#CreatedDate = #tmp,
#CharToAdd = 'XYZ',
#Start = 10,
#End = 20
EXEC [dbo].[Add_Details]
#VID = 2,
#CreatedDate = #tmp,
#CharToAdd = 'P1',
#Start = 10,
#End = 15
Output of working script:
Output of the stored procedure:
You need to filter by VID on the second insert. It's picking up rows from previous executions. Since it only picks up other rows where the ranges are overlapping it doesn't always do it. Run the procedure a few more times and you'll see the duplication amplified a lot more. The reason it didn't do this in the original code was because you were using a temp table that was recreated each time you ran it.
INSERT INTO [dbo].[TblDetails] (SID, Sno, [ConcatenatedText])
SELECT #SID
,Sno = A.RetVal
,ConcatenatedText = CONCAT(B.CharToAdd,A.RetVal)
FROM (
SELECT RetVal = CAST(RetVal AS INT)
FROM [dbo].[udf-Create-Range-Number](#Min,#Max,1)) A
JOIN dbo.TblMaster B ON A.RetVal BETWEEN B.Start AND B.[End]
WHERE B.VID = #VID -- <<<---------
)
On a side note I would highly recommend changing that function to type int rather than money.

SQL Trigger - How to update a table whenever another table in another database is being updated?

So I have a table called "persons" in a database test1:
CREATE TABLE [dbo].[persons](
[ID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](50) NULL,
[FirstName] [varchar](50) NULL,
[Job] [varchar](50) NULL,
[Extension] [char](10) NULL,
[EMail] [varchar](50) NULL,
[Dept] [int] NULL,
[MobileNumber] [char](10) NULL,
[District] [int] NULL,
[Status] [varchar](50) NULL,
[InOutStatus] [varchar](5) NULL,
[InOutDescr] [varchar](50) NULL,
[InOutDirections] [varchar](255) NULL,
[InOutReturn] [varchar](50) NULL,
[login] [varchar](50) NULL,
[StatusExpiry] [datetime] NULL
) ON [PRIMARY]
And a table called "Users" in a database test2:
CREATE TABLE [dbo].[Users](
[User_ID] [int] NOT NULL,
[Firstname] [nvarchar](50) NULL,
[Lastname] [nvarchar](50) NULL,
[Username] [nvarchar](50) NULL,
[Status] [nvarchar](50) NULL
) ON [PRIMARY]
What I'm trying to do is create a Trigger where if the FirstName, LastName, login, and/or Status column in the persons table is updated, then the same value is updated in its identical column in the Users table. This is a Trigger I came up with but it doesn't work:
ALTER TRIGGER [dbo].[UserUpdteTrig]
ON [dbo].[persons]
AFTER UPDATE
AS
BEGIN
DECLARE #uid int;
DECLARE #fname nvarchar(50);
DECLARE #lname nvarchar(50);
DECLARE #uname nvarchar(50);
DECLARE #stat nvarchar(50);
SELECT #fname = i.FirstName, #lname = i.LastName, #uname = i.login, #stat = i.Status
FROM inserted i
UPDATE [test2].[dbo].[Users]
SET Firstname = #fname , Lastname = #lname, Username = #uname, Status = #stat
FROM [test2].[dbo].[Users] u INNER JOIN inserted i ON u.User_ID = i.ID
END
I keep getting an error that says: The row value updated and deleted either do not make the row unique or they alter multiple rows, which the PK in both tables are all unique and the PK shouldn't be altered anyway.
You dont need any variables at all just a simple update should be enough.
ALTER TRIGGER [dbo].[UserUpdteTrig]
ON [dbo].[persons]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE u
SET u.Firstname = i.FirstName
, u.Lastname = i.Lastname
, u.Username = i.Username
, u.[Status] = i.[Status]
FROM [test2].[dbo].[Users] u
INNER JOIN inserted i ON u.[User_ID] = i.ID
END

Resources