Update a column in table with information from another table - sql

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]

Related

Create table with condition

I'm creating a table, which will have a date in one of two columns, or neither.
I'd like the third to auto populate with one of these values, without using an update.
CREATE TABLE [table1]
(
id [BIGINT] NOT NULL,
[date1] [DATETIME] NULL,
[date2] [DATETIME] NULL,
[date] AS (CASE
WHEN [date1] IS NOT NULL THEN [date1]
WHEN [date2] IS NOT NULL THEN [date2]
ELSE NULL
END)
)
This doesn't seem to work when I test using:
INSERT INTO [table1] (id, date1)
VALUES (1, GETDATE())
Can anyone help?
Your code appears to be fine, as seen in this db<>fiddle. However, I would suggest using COALESCE() instead of CASE:
CREATE TABLE [table1] (
id [bigint] NOT NULL,
[date1] [datetime] NULL,
[date2] [datetime] NULL,
[date] AS ( COALESCE(date1, date2) )
);
It is more concise.

Timestamp Field Incriminating

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.

Delete data based on a column and latest date

In the below Table, i need to get the query for table to Get the Delete query to remove the Unique Employee based on the older date of joining.
The result should have unique EmpNo, where the Doj is latest.
Below is the table data query
DECLARE #TableTest TABLE (
[Sid] [int] NULL,
[EmpNo] [int] NULL,
[EmpName] [nvarchar](50) NULL,
[DoJ] [int] NULL
)
INSERT INTO #TableTest VALUES
(101,'Suresh',20160517)
,(102,'Ravi',20160312)
,(101,'Ramu',20161022)
,(103,'Kumar',20160308)
,(104,'Gopi',20160411)
,(104,'Sridhar',20160620)
,(104,'Suresh',20161012)
Expected result
If you want to delete the rows, you can do:
with todelete as (
select tt.*,
row_number() over (partition by EmpNo order by Sid desc) as seqnum
from #tabletest
)
delete from todelete
where seqnum <> 1;

Range rows from SQL Server

I want to create paging using T-SQL. How can I select 10 rows from 11th row to 20th row?
I know I can do this with C# etc. But my question is about SQL Server.
Here is the table:
CREATE TABLE EarlyAccess(
[EarlyAccessUserId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[Lastname] [nvarchar](50) NOT NULL
)
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY earlyAccessUserId) rn
FROM earlyAccess
) q
WHERE rn BETWEEN 11 AND 20
ORDER BY
earlyAccessUserId
There is not such thing as n'th record in SQL unless you explicitly specify ordering.

Subquery Performance - Non Unique Column in Where Clause

I have two tables
Table Jobs
[ID] [int] IDENTITY(1,1) NOT NULL,
[title] [varchar](150) NULL,
[description] [text] NULL
Table JobSkills
[id] [int] IDENTITY(1,1) NOT NULL,
[jobId] [int] NULL,
[skill] [varchar](150) NULL
Shown above partial list of columns.
For table JobSkills I have indexed jobId column, column skill is full text indexed.
I have a stored procedure to get the list of jobs. sort of like this.
Select totalItems
,Id,title
from
(
Select Row_Number() over(Order By
CASE WHEN #sortBy Is Not Null AND #sortBy='relevance'
THEN
SkillMatchRank
END DESC
,CASE WHEN #sortBy Is Not Null AND #sortBy='date' THEN CreateDate END DESC
) As rowNumber
,COUNT(*) OVER() as totalItems
,ID,createDate,title
from Jobs J
OUTER APPLY dbo.GetJobSkillMatchRank(J.ID,#searchKey) As SkillMatchRank
Where
--where conditions here
) tempData
where
rowNumber>=CASE WHEN #startIndex>0 AND #endIndex>0 THEN #startIndex ELSE rowNumber END
AND rowNumber<=CASE WHEN #startIndex>0 AND #endIndex>0 THEN #endIndex ELSE rowNumber END
I have created a inline table valued function to get the skill matching rank.
CREATE FUNCTION [dbo].[GetJobSkillMatchRank]
(
#jobId int,
#searchKey varchar(150)
)
RETURNS TABLE
AS
RETURN
(
select SUM(ISNULL(JS2.[Rank],0)) as rank
from FREETEXTTABLE(JobSkills,skill,#searchKey) JS2
Where JS2.[Key] in (Select ID from JobSkills Where jobId=#jobId)
)
GO
Problem
Query runs super slow, more then a minute.
My observation
For the table valued function if I set jobId=1 (I do have a job with id=1) then it performs super fast as desired.
I understand that jobId is not unique column on JobSkills table.
In this case how could I improve the performance???
UDFs are great in certain cases, but the execution plans don't get cached like sprocs do. If you try using another derived table instead of a function, the query might perform better.