检查回文而不使用带条件的字符串函数

时间:2015-05-02 07:56:05

标签: sql string

我有一张桌子EmployeeTable 如果我只想要employeename具有1到5的字符的记录 将是回文并且还有条件,如总字符大于10然后4到8如果字符小于7然后2到5并且如果字符小于5然后所有字符将被检查并且那里是回文然后仅显示。

Examples :- neen will be display
            neetan not selected
            kiratitamara will be selected

我在字符串函数上尝试这个东西就像FOR第一种情况,比如名字少于5个字符长

SELECT SUBSTRING(EmployeeName,1,5),* from EmaployeeTable where 
          REVERSE (SUBSTRING(EmployeeName,1,5))=SUBSTRING(EmployeeName,1,5)

我想在没有字符串函数的情况下这样做, 任何人都可以帮我吗?

2 个答案:

答案 0 :(得分:0)

我真的不明白为什么你不想在你的查询中使用字符串函数,但这是一个解决方案。事先计算一切:

添加列:

 ALTER TABLE EmployeeTable
            ADD SubString AS 
            SUBSTRING(EmployeeName,
               (
               CASE WHEN LEN(EmployeeName)>10 
               THEN 4
               WHEN LEN(EmployeeName)>7
               THEN 2
               ELSE 1 END
               )
            ,
            (
               CASE WHEN LEN(EmployeeName)>10 
               THEN 8
               WHEN LEN(EmployeeName)>7
               THEN 5
               ELSE 5 END
               )
             PERSISTED
        GO

            ALTER TABLE EmployeeTable
            ADD Palindrome AS 
            REVERSE(SUBSTRING(EmployeeName,
               (
               CASE WHEN LEN(EmployeeName)>10 
               THEN 4
               WHEN LEN(EmployeeName)>7
               THEN 2
               ELSE 1 END
               )
            ,
            (
               CASE WHEN LEN(EmployeeName)>10 
               THEN 8
               WHEN LEN(EmployeeName)>7
               THEN 5
               ELSE 5 END
               )) PERSISTED
        GO

然后您的查询将如下所示:

    SELECT * from EmaployeeTable 
    where Palindrome = SubString

BUT! 这不是一个好主意。请告诉我们,为什么你不想使用字符串功能。

答案 1 :(得分:0)

DECLARE @cPalindrome VARCHAR(100) = 'SUBI NO ONIBUS'

SET @cPalindrome = REPLACE(@cPalindrome, ' ', '')
;WITH tPalindromo (iNo) AS (
    SELECT 1
     WHERE SUBSTRING(@cPalindrome, 1, 1) = SUBSTRING(@cPalindrome, LEN(@cPalindrome), 1) 
    UNION ALL
    SELECT iNo + 1
      FROM tPalindromo
     WHERE SUBSTRING(@cPalindrome, iNo + 1, 1) = SUBSTRING(@cPalindrome, LEN(@cPalindrome) - iNo, 1) 
       AND LEN(@cPalindrome) > iNo
)

SELECT IIF(MAX(iNo) = LEN(@cPalindrome), 'PALINDROME', 'NOT PALINDROME')
  FROM tPalindromo