Timestamp Field Incriminating - sql

I have a table as such (with a timestamp and a varbinary)
CREATE TABLE [dbo].[CASE]
(
[CASE_ID] [int] IDENTITY(1,1) NOT NULL,
[CASE_TITLE] [varchar](50) NOT NULL,
[CASE_STATUS] [varchar](50) NOT NULL,
[MODIFIED_TS] [timestamp] NOT NULL,
[SYNCED_TS] [varbinary](8) NULL
)
Then I add an item to it, and update it...
UPDATE [CASE]
SET CASE_STATUS = 'Something New'
WHERE CASE_ID = 1
When I do that, then I update the Synced_TS column:
UPDATE [CASE]
SET SYNCED_TS = MODIFIED_TS
WHERE CASE_ID = 1
But then, when I run this....
SELECT
*,
CAST(CONVERT(BIGINT, MODIFIED_TS) - CONVERT(INT, SYNCED_TS) AS DECIMAL)
FROM
[CASE]
WHERE
CAST(CONVERT(BIGINT, MODIFIED_TS) - CONVERT(INT, SYNCED_TS) AS DECIMAL) > 1
OR SYNCED_TS IS NULL
I have two values that are totally different, for example, A0D, and A0A, its OK they are different, but shouldn't it be A0D, and A0C?
MODIFIED_TS SYNCED_TS
---------------------------------------
0x0000000000000A0D 0x0000000000000A0A
The reason why its an issue, is that I am trying to convert it to an integer to compare it, so I can determine if the record needs to be synced or not.

Related

replace a computed column with a logic that works with INSERT

I have a table called tblPacks.
CREATE TABLE [dbo].[tblPacks]
(
[ID] [int] NOT NULL,
[BatchNumber] [varchar](30) NULL,
[PackID] VARCHAR(50),
[Status] [int] NULL
)
And a stored procedure spInsertPacks.
CREATE PROCEDURE spInsertPacks
#ID INT,
#BatchNumber VARCHAR(30),
#Count INT
AS
BEGIN
INSERT INTO tblPacks
Values
(
#ID,
#BatchNumber,
CONVERT([varchar](50),
'PK'+
case
when len(#ID)<=(3) then CONVERT([varchar](20),right((0.001)*#ID,(3)),0)
else CONVERT([varchar](20),#ID,0)
end,0),0)
END
If ID of data type INT inserted in an order like 1,2,3,4,5... the above logic works fine. But there is no restriction for a user to enter random numbers. I want a stored procedure to generate PackID(PK001,PK002..) sequence in order, irrespective of #ID and ID. Cannot be an identity Column. How can I do that?
Actually This PackID is a barcode If barcode already existed for Pack then that sequence may not be same with the sequence we used and Newly generated barcodes which we are generating will be in seuquence PK001
Sample Output:-
ID BatchNumber PackID Status
1 b1 PK001 0
1 b2 Pk002 0
5 b7 ABC768 0
3 b2 PK003 0
I have simplified the logic a bit for generating PackID
Add a new column(identifier) for identifying the code and use it for PackID generation and for sequence use Identity column
CREATE TABLE [dbo].[tblPacks]
(
Iden_ID INT IDENTITY(1, 1),
[ID] [INT] NOT NULL,
[BatchNumber] [VARCHAR](30) NULL,
[Identifier] [VARCHAR](50),
[PackID] AS [Identifier]
+ CASE
WHEN Iden_ID <= 999 THEN RIGHT('00' + CONVERT(VARCHAR(3), ID), 3)
ELSE CONVERT([VARCHAR](20), ID, 0)
END,
[Status] [INT] NULL
)
To check the working
INSERT INTO [dbo].[tblPacks]
([ID],identifier,[BatchNumber],[Status])
VALUES (1,'pk','bat',1)
SELECT *
FROM [tblPacks]

SQL loop executes but new old values are over written

As my question title says, my program loops but all of my values I updated are being overwritten. Here's the code posted below. Say minRownum is 1 and max is 12, I see the loop execute 12 times correctly and min gets updated +1 each time. But in the end result, only the final row in my column whose RowNum is 12 have any values
I'm not exactly sure why overwriting is occurring since I'm saying "Update it where the rownumber = minrownumber" then I increment minrownum.
Can anyone point to what I am doing wrong? Thanks
WHILE (#MinRownum <= #MaxRownum)
BEGIN
print ' here'
UPDATE #usp_sec
set amount=(
SELECT sum(amount) as amount
FROM dbo.coverage
inner join dbo.owner
on coverage.api=owner.api
where RowNum=#MinRownum
);
SET #MinRownum = #MinRownum + 1
END
PS: I edited this line to say (below) and now every value has the same wrong number (its not distinct but duplicated to all.
set amount = (SELECT sum(amount) as amount
FROM dbo.coverage
INNER JOIN dbo.owner ON coverage.api = owner.api
where RowNum=#MinRownum
) WHERE RowNum = #MinRownum;
Tables:
CREATE TABLE dbo. #usp_sec
(
RowNum int,
amount numeric(20,2),
discount numeric(3,2)
)
CREATE TABLE [dbo].[handler](
[recordid] [int] IDENTITY(1,1) NOT NULL,
[covid] [varchar](25) NULL,
[ownerid] [char](10) NULL
)
CREATE TABLE [dbo].[coverage](
[covid] [varchar](25) NULL,
[api] [char](12) NULL,
[owncovid] [numeric](12, 0) NULL,
[amount] [numeric](14, 2) NULL,
[knote] [char](10) NULL
)
CREATE TABLE [dbo].[owner](
[api] [char](12) NOT NULL,
[owncovid] [numeric](12, 0) NULL,
[ownerid] [char](10) NOT NULL,
[officer] [char](20) NOT NULL,
[appldate] [date] NOT NULL
)
Your UPDATE statement needs its own WHERE clause. Otherwise, each UPDATE will update every row in the table.
And the way you have this written, your subquery still needs its WHERE clause too. In fact, you need to definitively correlate the subquery to your table's (#usp_sec) rows. We cannot tell you how that should be done without more information such as your table definitions.

How to write trigger to generate sequence number for repeated value

I need to generate sequence number for repeated value in a SQL Server table.
Here's my table
CREATE TABLE [dbo].[tbl_all_purple_flag_level](
[Sno] [int] IDENTITY(1,1) NOT NULL,
[Id] [varchar](50) NULL,
[Name] [varchar](50) NULL,
[Score] [varchar](50) NULL,
[Disability_Level] [varchar](50) NULL,
[visited_count] [varchar](50) NULL,
[Date] [varchar](50) NULL
)
If id has repeated numbers, I need visited_count to be a sequence number (1, 2, 3...)
I tried this code
SELECT
id,
RIGHT('0'+ CAST((ROW_NUMBER() OVER (Partition By id Order By id)) as varchar(2)), 2) as duplicate_id
FROM
tbl_all_purple_flag_level
It works fine but I don't know how to do in trigger. Can anyone help me? Thanks!
ALTER TRIGGER tr_After_Update_Inser
ON [dbo].[tbl_all_purple_flag_level]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
WITH Updateable
AS
(
SELECT [Sno], id, [visited_count],
RIGHT('0'+ CAST((ROW_NUMBER() OVER (Partition By id Order By id, [Date] DESC)) as varchar(2)), 2) as duplicate_id
FROM tbl_all_purple_flag_level
)
UPDATE Updateable
SET [visited_count] = duplicate_id
END
One thing I would like to point out, SQL Server has Data types to store almost all kinds of data, I can see you are saving Dates in Varchar data type and IDs and Score all in varchar data type, Sql Server has Date data type to store date values. why would you use varchar for all the columns dont know but I think you should consider using appropriate data types for your column instead of using VARCHAR for everything.

Update a column in table with information from another table

Im already have this:
USE [AdventureWorks2012];
--- somewhere create table
IF OBJECT_ID('[dbo].[PersonPhone]','U') IS NOT NULL
DROP TABLE [dbo].[PersonPhone]
CREATE TABLE [dbo].[PersonPhone](
[BusinessEntityID] [int] NOT NULL,
[PhoneNumber] nvarchar(25) NOT NULL,
[PhoneNumberTypeID] [int] NOT NULL,
[ModifiedDate] [datetime] NOT NULL)
--- and append new column
ALTER Table [dbo].[PersonPhone]
ADD [StartDate] date NULL
--- after this, i want copy dates in this column (at another table, we increase dates by one)
UPDATE [dbo].[PersonPhone]
SET [StartDate] = [NewTable].[NewDate]
FROM (
SELECT DATEADD(day, 1, [HumanResources].[EmployeeDepartmentHistory].[StartDate]) AS [NewDate],
row_number() over(order by (select 1)) AS [RN]
FROM [HumanResources].[EmployeeDepartmentHistory]
) [NewTable]
How to improve query to copy the values ​​from [NewTable] to [dbo].[PersonPhone].[StartDate] row?
At your Update:
UPDATE [dbo].[PersonPhone]
SET [StartDate] = DATEADD(day, 1, [HumanResources].[EmployeeDepartmentHistory].[StartDate])
FROM [HumanResources].[EmployeeDepartmentHistory]
GO
SELECT row_number() over(order by (select 1)) AS [RN] FROM [HumanResources].[EmployeeDepartmentHistory]

SQL Case Statement with a Subselect

select case when exists(
select top 1 1
from dg_world_records wr (nolock)
where wr.gametypeid = 4
and wr.playerid = 1
)
then totaltime = (select min(totaltime) from dg_world_records (nolock) where playerid = 1 and gametypeid = 4)
else totaltime = (select max(totaltime) from dg_world_records (nolock) where gametypeid = 4)
end
My guess is that this can't be done, but I'm trying to do a subselect within a sql case statement. Is this possible?
I'm trying to do a lookup based of finding or not finding a value in a table. I can do this by breaking up the statement, but I was wondering if it's possible to do this in a single statement.
Here is the table schema:
CREATE TABLE [dbo].[DG_WORLD_RECORDS](
[WorldRecordId] [int] IDENTITY(1,1) NOT NULL,
[GameTypeId] [int] NOT NULL,
[PlayerId] [int] NOT NULL,
[NumberOfValues] [int] NOT NULL,
[TotalTime] [int] NOT NULL,
[DateOfRecord] [datetime] NOT NULL,
[GameId] [int] NULL,
[UTCInserted] [datetime] NOT NULL CONSTRAINT [DF_DG_WORLD_RECORDSII_UTCInserted] DEFAULT (getutcdate()),
[UTCUpdated] [datetime] NOT NULL CONSTRAINT [DF_DG_WORLD_RECORDSII_UTCUpdated] DEFAULT (getutcdate()),
[SrvName] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF_DG_WORLD_RECORDSII_SrvName] DEFAULT (##servername),
CONSTRAINT [PK_DG_WORLD_RECORDS] PRIMARY KEY CLUSTERED
(
[WorldRecordId] ASC
)
)
Don't know why you are writing this crazy query, but to answer your question, yes it could be done, just move your assignment out of the case statement:
select totaltime = CAST (
case when exists(
select *
from dg_world_records wr (nolock)
where wr.gametypeid = 4 and wr.playerid = 1)
then (select min(totaltime) from dg_world_records (nolock) where playerid = 1 and gametypeid = 4)
else (select max(totaltime) from dg_world_records (nolock) where gametypeid = 4)
end AS INT)