Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following table-valued function for splitting strings. This works fine, was cribbed from elsewhere on the web, and I would have thought isn't the cause of the problem but is included in case it's relevant:

CREATE FUNCTION dbo.StringSplit (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
  WITH Pieces(pn, start, stop) AS (
    SELECT 1, 1, CHARINDEX(@sep, @s)
    UNION ALL
    SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
    WHERE stop > 0
  )
  SELECT pn,
    SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
  FROM Pieces
)
GO

This enables the following line:

SELECT * FROM dbo.StringSplit('.', 'this.is.a.string.to.split')

to produce

 pn | s
----+--------
 1  | this
 2  | is
 3  | a
 4  | string
 5  | to
 6  | split

My aim in this is to obtain a list of file extensions from a table which contains a large number of filenames. To that end, I used the above table-valued function to split each filename:

SELECT
  doc_id,
  doc_file_name,
  (SELECT TOP 1 s FROM dbo.StringSplit('.', doc_file_name) ORDER BY pn DESC) AS extension
FROM
  ai_docs_core

Having SQL Server Enterprise Manager check the syntax on that gives me a syntax error on the line containing the function:

Msg 102, Level 15, State 1, Line 34
Incorrect syntax near 'doc_file_name'.

The following doesn't do what I need (obviously, because it's using a set variable), but it doesn't cause a syntax error:

DECLARE @foo VARCHAR(512) = 'my_filename.doc'
SELECT
  doc_id,
  doc_file_name,
  (SELECT TOP 1 s FROM dbo.StringSplit('.', @foo) ORDER BY pn DESC) AS extension
FROM
  ai_docs_core

So the question is: why does using a specific field name as a parameter to the function cause a syntax error, and how can I achieve what I want?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

I would guess that the database is set to compatibility mode 80 or lower.

See sp_dbcmptlevel

This is usually the cause if it happens in a FROM clause

You can also write it like this

SELECT
  a.doc_id,
  a.doc_file_name,
  foo.extension 
FROM
  ai_docs_core a
  OUTER APPLY
  (SELECT TOP 1 s AS extension
   FROM dbo.StringSplit('.', a.doc_file_name)
   ORDER BY pn DESC
  ) foo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...