如何 select 仅 SQL 服务器中 table 列的部分数据

how to select only some part of data from a table column in SQL SERVER

我已经创建了一个 SQL SERVER 脚本。首先请检查脚本

SELECT
  W.RequesterName + ' ' + +'on ' + CONVERT(varchar(20), W.Requested, 111) + ' ' + CONVERT(varchar(20), W.Requested, 108) + ' ' + (CASE
    WHEN DATEPART(HOUR, W.Requested) > 12 THEN 'PM'
    ELSE 'AM'
  END) AS 'Request Detail',
  W.TakenByName,
  W.Reason,
  CONVERT(varchar(20), W.TargetDate, 111) + '   (' + CONVERT(nvarchar(max), CAST(W.TargetHours AS float)) + ')' + ' hr' AS targetWorkDetails,
  W.PriorityDesc + '/' + W.TypeDesc AS priorityDesc,
  W.SupervisorName,
  W.ShopID,
  W.RepairCenterName,
  W.RequesterPhone,
  A.Location3Name,
  A.ParentLocation,
  A.ParentLocationAll,
  W.AssetName,
  W.AssetName + '(' + CONVERT(nvarchar(20),w.AssetID,101) + ')' AS AssetDetails

FROM WO W
INNER JOIN AssetHierarchy A
  ON W.AssetPK = A.AssetPK
WHERE w.WOPK = 10144 --INNER JOIN AssetHierarchy ON WO.AssetPK=AssetHierarchy.AssetPK   

现在请检查我的输出

现在请检查突出显示的属性 'ParentLocationAll'。我的任务是在
标签开始之前获取 ParentLocationAll 数据。例如,在 ParentLocationAll 列中,我们有值 'Wood Buffalo
Main Building' 我只想取 'Wood Buffalo' 。我想再举一个例子:假设我们在 'ParentLocationAll' 列中有值 'calgery
abcd'。那么我只需要 'calgery' 而不是整个值。 我已经努力但无法解决问题。请帮我做点好事 建议。提前致谢。

在这里使用 PATINDEXLEFT 的组合可能有效:

WITH yourTable AS (
    SELECT 'Wood Buffalo<br>Main Building' AS ParentLocationAll
)

SELECT
    LEFT(ParentLocationAll d, PATINDEX('%<%>%', ParentLocationAll) - 1) AS ParentLocation
FROM yourTable;

Wood Buffalo  <-- output

Demo

这是否适用于所有情况取决于您的数据。例如,如果您的父位置列有随机的 <> 符号,没有出现在 HTML 标签的上下文中,那么我的解决方案可能会失败。

严格基于下面代码段提供的输入数据即可完成工作 -

create table #table (ParentLocationAll nvarchar(1000))
insert into #table (ParentLocationAll) select 'Wood Buffalo Main Building'
insert into #table (ParentLocationAll) select 'calgery abcd'
select 
       case when len(ParentLocationAll) - len(replace(ParentLocationAll, ' ', '')) = 1 
       then LEFT(ParentLocationAll, charindex(' ', ParentLocationAll) - 1) 
       else SubString(ParentLocationAll, 1, CharIndex(' ', ParentLocationAll, CharIndex(' ', ParentLocationAll) + 1)) end as ParentLocationAll
from #table

所以,这里的代码只是检查字符串中 spaces(' ') 的数量,如果计数为 1,那么它将提取字符串直到找到第一个 space 否则它会在你的主字符串中找到第二个 space 并提取字符串直到那时。