在SQL存储过程中提取字符串的某些部分

时间:2011-11-17 08:59:30

标签: sql string

此刻我有这个存储过程。我想将String ChanceOfSuccess限制为只有“40%”这样的百分比。现在,字符串读取的内容为“40% - 思考它”。最好的方法是什么?

CREATE PROCEDURE [dbo].[procActivity_SelectbyOutstandingActivitiesNew]
AS
SELECT  C.[Name] AS [Customer], 
        C.CustomerId AS [CustomerID],
        E.FirstName + ' ' + E.Surname AS [Employee],
        AT.[TypeName] AS [Activity Type],
        A.[ActivityDate] AS ActivityDate,
        A.NextActivityDate,
        A.[ChanceOfSuccess] AS ChanceOfSuccess,
        A.[Comments] AS Comments,
        U.Surname + ' ' + U.FirstName AS [User],
        E.EmployeeId,
        A.ActivityId,
        CONVERT(INT, SUBSTRING(A.ChanceOfSuccess, 0, CHARINDEX ('%',A.ChanceOfSuccess))) AS [Success Percentage],
        A.[IsComplete]

FROM    Customer C
INNER JOIN Activity A ON A.CustomerId = C.CustomerId
INNER JOIN Employee E ON E.EmployeeId = A.EmployeeId AND E.CustomerId = C.CustomerId
INNER JOIN [ActivityType] AT ON A.[ActivityTypeId] = AT.[ActivityTypeId]
INNER JOIN [User] U ON A.[UserId] = U.[UserId]
LEFT OUTER JOIN Activity A2 ON A.CustomerId = A2.CustomerId AND A.UserId = A2.UserId AND A2.ActivityDate > A.ActivityDate
WHERE   C.[IsDeleted] = 0
AND     A.NextActivityDate <= GETDATE()
AND     E.IsDeleted = 0
AND     A.IsDeleted = 0
AND (A2.ActivityId IS NULL OR A2.IsDeleted > 0)
AND CONVERT(INT, SUBSTRING(A.ChanceOfSuccess, 0, CHARINDEX ('%',A.ChanceOfSuccess))) < 100
ORDER BY A.NextActivityDate ASC, Customer, A.ActivityDate ASC, [Success Percentage] DESC
GO

2 个答案:

答案 0 :(得分:1)

作业?你显然没有写原始查询,因为它已经在做那项工作了。

该行:

CONVERT(INT, SUBSTRING(A.ChanceOfSuccess, 0, CHARINDEX ('%',A.ChanceOfSuccess))) AS [Success Percentage],

已经做了你想要的事情,然后将其转换为int,所以删除转换,你应该有你想要的。

DECLARE @v VARCHAR(50) = '40% - Thinking about it'

SELECT @V, SUBSTRING(@V, 0, charindex('%', @V)+1)

答案 1 :(得分:0)

以下是有关如何重写代码的一些消息:

create view [v_OutstandingActivities]
AS
SELECT  C.[Name] AS [Customer], 
        C.CustomerId AS [CustomerID],
        E.FirstName + ' ' + E.Surname AS [Employee],
        AT.[TypeName] AS [ActivityType],
        A.[ActivityDate] AS ActivityDate,
        A.NextActivityDate,
        A.[ChanceOfSuccess] AS ChanceOfSuccess,
        A.[Comments] AS Comments,
        U.Surname + ' ' + U.FirstName AS [UserName],
        E.EmployeeId,
        A.ActivityId,
        replace(A.ChanceOfSuccess, '%', '')+0 AS [SuccessPercentage],
        A.[IsComplete]

FROM    Customer C
INNER JOIN Activity A ON A.CustomerId = C.CustomerId
INNER JOIN Employee E ON E.EmployeeId = A.EmployeeId AND E.CustomerId = C.CustomerId
INNER JOIN [ActivityType] AT ON A.[ActivityTypeId] = AT.[ActivityTypeId]
INNER JOIN [User] U ON A.[UserId] = U.[UserId]
LEFT OUTER JOIN Activity A2 ON A.CustomerId = A2.CustomerId AND A.UserId = A2.UserId 
AND A2.ActivityDate > A.ActivityDate AND (A2.IsDeleted > 0)
WHERE   C.[IsDeleted] = 0
AND     A.NextActivityDate <= GETDATE()
AND     E.IsDeleted = 0
AND     A.IsDeleted = 0
AND replace(A.ChanceOfSuccess, '%', '') < 100