Using a previously done example found here, I got stuck with a unique situation I'm having difficulty getting by.
Here is the adapted code
declare #RandomString table (ID int not null,ItemValue varchar(500) not null)
insert into #RandomString(ID,ItemValue)
values (1,'<Strings><B1>String1</B1><B2>String2</B2><B3>String3</B3><B4>String4</B4></Strings>')
declare #SearchCharReplacement table (Original varchar(500) not null,Replacement varchar(500) not null)
Insert into #SearchCharReplacement(Original, Replacement)
values ('String1', 'abc'), ('String2', 'efg'),
('String3', 'hij'), ('String4', 'klm')
;With Replacements as (
select ID,ItemValue,0 as RepCount
from #RandomString
union all
select ID,SUBSTRING(REPLACE(ItemValue,Original, Replacement),1,500),rs.RepCount+1
from Replacements rs
inner join #SearchCharReplacement scr on CHARINDEX(scr.Original,rs.ItemValue) > 0
)
, FinalReplacements as (
select ID,ItemValue,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY RepCount desc) as rn
from Replacements
)
update rs set ItemValue = fr.ItemValue
from #RandomString rs
inner join FinalReplacements fr on rs.ID = fr.ID and rn = 1
select * from #RandomString
Result is
<Strings><B1>abc</B1><B2>def</B2><B3>ghi</B3><B4>jkl</B4></Strings>
What I would really like is
<Strings><B1>String1|abc</B1><B2>String2|def</B2><B3>String3|ghi</B3><B4>String4|jkl</B4></Strings>
Any help is much appreciated
With some internal help we came up with
Declare #XMLData Varchar(max) = N'<JEI><B1>String1</B1><B2>String2</B2><B3>FRED</B3><B4/></JEI>'
Declare #T Table(XMLCol xml)
Insert into #T select #XMLData
declare #SearchCharReplacement table (Original varchar(500) not null, Replacement varchar(500) not null)
Insert into #SearchCharReplacement(Original, Replacement)
values ('String1', 'abc'), ('String2', 'efg'),
('String3', 'hij'), ('String4', 'klm')
;With Strings as
(
SELECT a.value('B1[1]', 'varchar(15)') as B1
,a.value('B2[1]', 'varchar(15)') as B2
,a.value('B3[1]', 'varchar(15)') as B3
,a.value('B4[1]', 'varchar(15)') as B4
,CAST(XMLData.XMLCol as varchar(max)) as Data
FROM #T as XMLData
Cross APPLY XmlData.XMLCol.nodes('/JEI') AS JEI(a)
)
--SELECT * from strings
SELECT *
,REPLACE(
REPLACE(
REPLACE(
REPLACE(ST.Data,
ST.B1, COALESCE(ST.B1 + '|' + SCR1.Replacement ,ST.B1))
,ST.B2, COALESCE(ST.B2 + '|' + SCR2.Replacement, ST.B2))
,ST.B3, COALESCE(ST.B3 + '|' + SCR3.Replacement, ST.B3))
,ST.B4, COALESCE(ST.B4 + '|' + SCR4.Replacement, ST.B4))
AS x
FROM #T RS
CROSS JOIN Strings ST
LEFT OUTER JOIN #SearchCharReplacement SCR1
on SCR1.Original = ST.B1
LEFT OUTER JOIN #SearchCharReplacement SCR2
on SCR2.Original = ST.B2
LEFT OUTER JOIN #SearchCharReplacement SCR3
on SCR3.Original = ST.B3
LEFT OUTER JOIN #SearchCharReplacement SCR4
on SCR4.Original = ST.B4
Related
I have the following data in my Database:
Id MachineName CategoryName CounterName InstanceName RawValue
11180 SERVER64 Process ID Process w3wp#2 2068
11180 SERVER64 Process Working Set w3wp#2 9310208
Now I want to achieve that if I find the value '2068' for the "ID Process" Countername then I want to retrieve the Working Set RawValue. So based on the value of ID Process I now the [InstanceName] = w3wp#2 and therefore I want the value to retrieve = 9310208
Now I tried different SQL queries:
SELECT *
FROM [dbo].[LoadTest]
WHERE [LoadTestRunId] = '11180' and [CategoryName] = 'Process' and [InstanceName] like 'w3wp%'
But I need a filter. Can anyone guide me into the right direction?
This here will help you. I used variable because you need to find a specific ID
SQL Code
declare #myt table (id int,MachineName nvarchar(50),CategoryName nvarchar(50),CounterName nvarchar(50),InstanceName nvarchar(50),RawValue int)
insert into #myt
values
(11180 ,'SERVER64','Process','ID Process','w3wp#2',2068),
(11180 ,'SERVER64','Process','Working Set','w3wp#2',9310208)
declare #FindID int
Set #FindID = 2068;
with IdProcess as (
Select * from #myt
where RawValue = #FindID and CounterName = 'ID Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.InstanceName = b.InstanceName and b.CounterName='Working Set'
SQL Code without variable based on ID and InstanceName
with IdProcess as (
Select * from #myt
where CounterName = 'ID Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.id = b.id and a.InstanceName = b.InstanceName and b.CounterName='Working Set'
SQL Code with CategoryName filter
with IdProcess as (
Select * from #myt
where CounterName = 'ID Process' and CategoryName = 'Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.id = b.id and a.InstanceName = b.InstanceName and b.CounterName='Working Set'
where b.CategoryName = 'Process'
Result
This will execute.
Select * from (SELECT ROW_NUMBER() OVER(PARTITION BY LoadTestRunId ORDER BY LoadTestRunId DESC) as row,*
FROM [dbo].[LoadTest]) t1 where row=1
with your where clause
Select * from (SELECT ROW_NUMBER() OVER(PARTITION BY LoadTestRunId ORDER BY LoadTestRunId DESC),*
FROM [dbo].[LoadTest]) t1 where t1=1
and [LoadTestRunId] = '11180' and [CategoryName] = 'Process' and [InstanceName] like 'w3wp%'
I have a query in SQL Server.
There is a temporary table #final as shown below
I want to fetch only single row of each project having Maximum EXPECTEDENDDATE.
try below one :-
Select f1.*
From #Final As f1 With (Nolock)
Join
(
Select Max(EXPECTEDENDDATE) As EXPECTEDENDDATE
,EmployeeCode
,ProjectCode
From #Final As t With (Nolock)
Group By t.EmployeeCode
,t.ProjectCode
) As f On f1.EmployeeCode = f.EmployeeCode
And f1.ProjectCode = f.ProjectCode
ANd f1.EXPECTEDENDDATE = f.EXPECTEDENDDATE
Update
Declare #final Table
(
EmployeeCode Int
,ProjectName Varchar(500)
,ExpectedStartDate Date
,ExpectedEndDate Date
,DaysAllocated Int
)
Declare #SameStartProjects Table
(
EmployeeCode Int
,ProjectName Varchar(500)
,RowNum BigInt
)
Insert Into #final(EmployeeCode,ProjectName,ExpectedStartDate,ExpectedEndDate,DaysAllocated) Values
(1149,'INT-Vibrant Web','2015-04-22','2015-05-21',14)
,(1149,'INT-Vibrant Web','2015-05-22','2015-05-31',6)
,(1149,'Praetorian Track Off','2015-03-19','2015-05-22',15)
,(1149,'Praetorian Track Off','2015-03-19','2015-06-11',20)
,(1149,'RPost Phase ||','2015-05-01','2015-05-31',20)
Insert Into #SameStartProjects(EmployeeCode,ProjectName,RowNum)
Select p.EmployeeCode
,p.ProjectName
,Row_Number() Over(Partition By p.ExpectedStartDate Order By p.ExpectedStartDate) As RowNum
From #final As p
Select s.*
From #final As s
Join
(
Select f.EmployeeCode
,f.ProjectName
,f.ExpectedStartDate
,Max(f.ExpectedEndDate) As ExpectedEndDate
,Max(sp.RowNum) As RowNum
From #final As f
Join #SameStartProjects As sp On f.EmployeeCode = sp.EmployeeCode
And f.ProjectName = sp.ProjectName
Group By f.EmployeeCode
,f.ProjectName
,f.ExpectedStartDate
) As f On s.EmployeeCode = f.EmployeeCode
And s.ProjectName = f.ProjectName
And s.ExpectedEndDate = f.ExpectedEndDate
above, #final is your #final table, and i have not taken all the attributes for example
Output:-
Is it possible to do an update query like this? It may not be, just a thought I had as to possibly a solution to my predicament of terrible data-structure. What I am trying to accomplish is:
To update the table prodinformation with a count where the entrytype exists in table vet
Set #location varchar(100), #entrydate datetime
Set #location = 'server01.database01.dbo.manhunt
Set #entrydate = GetDate()
Update prodinformation
Set totalenteredtoday = abc.te
FROM prodinformation d
JOIN (SELECT Count(ID)
from #location
WHERE entrytype IN (
Select validentrytype
from vet
where ltrim(rtrim(entrydate)) = #entrydate) As te
Update d
Set totalenteredtoday = te.IdCount
FROM prodinformation As d
JOIN
(
Select [someJoinAttribute]
,Count(ID) As IdCount
From #location
Where entrytype IN ( Select validentrytype
From vet With (Nolock)
Where ltrim(rtrim(entrydate)) = #entrydate
)
Group By [someJoinAttribute]
) As te On d.[someAttribute] = te.[someJoinAttribute]
here [someJoinAttribute] would be the column/attribute to be used to perform join operation
Due to the first two comments I've removed all my own code and placed the example directly from 4 guys here.
I'm interested in how the 'select #first_id' should be coded. The example shows the rows being pulled using joins and I would expect that the first_id wouldn't be a valid place to start because it doesn't use the same join syntax.
CREATE PROCEDURE [dbo].[usp_PageResults_NAI]
(
#startRowIndex int,
#maximumRows int
)
AS
DECLARE #first_id int, #startRow int
-- A check can be added to make sure #startRowIndex isn't > count(1)
-- from employees before doing any actual work unless it is guaranteed
-- the caller won't do that
-- Get the first employeeID for our page of records
SET ROWCOUNT #startRowIndex
SELECT #first_id = employeeID FROM employees ORDER BY employeeid
-- Now, set the row count to MaximumRows and get
-- all records >= #first_id
SET ROWCOUNT #maximumRows
SELECT e.*, d.name as DepartmentName
FROM employees e
INNER JOIN Departments D ON
e.DepartmentID = d.DepartmentID
WHERE employeeid >= #first_id
ORDER BY e.EmployeeID
SET ROWCOUNT 0
GO
You can to efficient paging using ROW_NUMBER()
DECLARE #skipRows Int = 10 --Change to input parameter to sp
DECLARE #takeRows Int = 20 --Change to input parameter to sp
SELECT *
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY a.DateCreated) As RowNumber,
a.PKID,
a.AlertUrl,
a.AlertDescription,
a.Users_PKID_creator,
dbo.Users_GetFullName(a.Users_PKID_creator) as Users_FullName,
a.Dealers_PKID,
d.Dealer,
dbo.convertDateFromUTC(a.DateCreated, #dealers_pkid) as DateCreated,
dbo.convertDateFromUTC(a.DateCreated, #dealers_pkid) as ComparisonDate,
dbo.convertDateFromUTC(a.DateModified, #dealers_pkid) as DateModified,
a.Active,
a.Contacts_PKID,
dbo.Contacts_GetFullName(a.Contacts_PKID) as Contacts_FullName
from Alerts a
join Dealers d on d.PKID = a.Dealers_PKID
where a.DateCreated between dbo.convertDateToUTC(#datetimeDateStart, #dealers_pkid) and dbo.convertDateToUTC(#datetimeDateEnd, #dealers_pkid)
and a.Active = #bitActive
and a.PKID >= #first_id
) AS [t1]
WHERE [t1].RowNumber BETWEEN #skipRows + 1 AND #skipRows + #takeRows
I have 4 tables:
Table1
ContentID(pk)
ContentGUID
Description
SiteID
CategoryID
StartDate
DisplayName
ParentId
AssignedAuthors
AssignedEditors
CreatedBy
U.UserName
Created
ModifiedBy
UserName
Modified
Priority
Table2
ContentID(fk)
versionid(pk)
page
Table3
apprhistroyid(pk)
verstionid(fk)
approvalstatusid(fk)
Table4
approvalstatusid(pk)
statusname
I want the total details of table1 and table4. I have tried the following procedure:
ALTER PROCEDURE [dbo].[DEV_SiteAdmin_Menu_GetItem_ALL_TEMP]
#SiteID Int
AS
DECLARE #VersionID int, #ApprovalStatusID int,#StatusName nvarchar(max),#ContentID Int,#Rowcount int
DECLARE #TEMP INT
--set #ApprovalStatusID=5;
--set #StatusName ='New';
set #Rowcount=(select max(ContentID)from dev_content where SiteID=#SiteID)
set #ContentID=(select min(ContentID) from dev_content where SiteID=#SiteID)
SET #TEMP=#ContentID
IF(#Rowcount>=1)
BEGIN
WHILE #Rowcount>1
BEGIN
SET #Rowcount=#Rowcount-1
set #ApprovalStatusID=
CASE
WHEN exists (SELECT VersionID from DEV_ContentVersion WHERE ContentID=#TEMP)
THEN (SELECT ApprovalStatusID FROM DEV_ApprovalStatus WHERE ApprovalStatusID=(SELECT ApprovalStatusID FROM DEV_ApprovalHistory WHERE VersionID=(SELECT VersionID from DEV_ContentVersion WHERE ContentID=(select ContentID from dev_content where ContentID=#ContentID and SiteID=#SiteID)))) else 5 end
set #StatusName=
case
when (#ApprovalStatusID != 5)
then
(SELECT StatusName FROM DEV_ApprovalStatus WHERE ApprovalStatusID=#ApprovalStatusID)
else
'New'
end
SELECT DISTINCT [ContentID]
,[ContentGUID]
,[Description]
,[SiteID]
,[CategoryID]
,[StartDate]
,[DisplayName]
,[ParentId]
,[AssignedAuthors]
,[AssignedEditors]
,[CreatedBy]
,U.UserName 'CreatedUser'
,dbo.fnGetUserNamesFromUserIds([AssignedAuthors],',') 'Authors'
,dbo.fnGetUserNamesFromUserIds([AssignedEditors],',') 'Editors'
,[Created]
,[ModifiedBy]
,U1.UserName 'ModifiedUser'
,[Modified]
,[Priority]
,#ApprovalStatusID [ApprovalStatusID]
,#StatusName [StatusName]
FROM [DEV_Content] C
INNER JOIN dbo.aspnet_Users U ON U.UserId=C.CreatedBy
INNER JOIN dbo.aspnet_Users U1 ON U1.UserId=C.ModifiedBy
WHERE C.SiteID=#SiteID AND [ContentID] = #TEMP
SET #TEMP= #TEMP+1
END
END
else
print 'error'
Where I am getting n no.of rowa that is it returns per 1 contentid 1 row instead I want all return values as one table.
I think your whole query can be boiled down to:
SELECT
[ContentID]
,[ContentGUID]
,[Description]
,[SiteID]
,[CategoryID]
,[StartDate]
,[DisplayName]
,[ParentId]
,[AssignedAuthors]
,[AssignedEditors]
,[CreatedBy]
,U.UserName as CreatedUser
,dbo.fnGetUserNamesFromUserIds([AssignedAuthors],',') as Authors
,dbo.fnGetUserNamesFromUserIds([AssignedEditors],',') as Editors
,[Created]
,[ModifiedBy]
,U1.UserName as ModifiedUser
,[Modified]
,[Priority]
,COALESCE(ah.ApprovalStatusID,5) as ApprovalStatusID
,COALESCE(ast.StatusName,'New' as StatusName
FROM
[DEV_Content] C
INNER JOIN
dbo.aspnet_Users U
ON
U.UserId=C.CreatedBy
INNER JOIN
dbo.aspnet_Users U1
ON
U1.UserId=C.ModifiedBy
left join
DEV_ContentVersion cv
inner join
DEV_ApprovalHistory ah
on
cv.VersionID = ah.VersionID
inner join
DEV_ApprovalStatus ast
on
ah.ApprovalStatusID = ast.ApprovalStatusID
on
C.ContentID = cv.ContentID
WHERE
C.SiteID=#SiteID
But I have to admit, I'm not sure what the DISTINCT was meant to be doing in there.