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