0

I'm trying to create function that takes data from table, replaces certain characters and returns replaced data. Function will be executed when called for.

CREATE FUNCTION convert_lat(@rawtxt NVARCHAR)
RETURNS NVARCHAR(50)
AS
BEGIN
    DECLARE @raw_mon NVARCHAR(50);

    SELECT @raw_mon = REPLACE (r.mongol, N'ф', 'f')
    FROM Connection.dbo.raw r
    WHERE r.mongol = @rawtxt

    RETURN @raw_mon;
END;
GO

UPDATE [Connection].[dbo].[raw] 
SET [mongol] = dbo.convert_lat(mongol) 
WHERE [mongol] LIKE N'ф%';

After I execute the UPDATE statement, characters that supposed to be replaced are not replaced but whole row becomes null.

5
  • So, what is the issue ? Commented May 9, 2018 at 12:49
  • Are you having issues? Glancing at it, it looks like accurate SQL code Commented May 9, 2018 at 12:52
  • Maybe you need a function that returns a table - TVF ? That code doesn't make much sense to me. Commented May 9, 2018 at 12:52
  • Try converting your scalar function to a table valued function, although it should work as it is now as long as your select retrieves just 1 row. Commented May 9, 2018 at 12:54
  • 3
    The main issue is that you didn't specify the size of your parameter. The default for a parameter is 1. ALWAYS specify the size. sqlblog.org/2009/10/09/… Commented May 9, 2018 at 13:08

2 Answers 2

2

As said in the comments, use ITVF function

CREATE FUNCTION convert_lat(@rawtxt nvarchar (400))
RETURNS TABLE AS RETURN
SELECT raw_mon = REPLACE (@rawtxt, N'ф', 'f')

GO

Use it:

SELECT R.* , F.raw_mon
FROM Connection.dbo.raw r
CROSS APPLY convert_lat (R.mongol) F
Sign up to request clarification or add additional context in comments.

2 Comments

I will try it. Is it right way to include a lot of characters in : REPLACE (@rawtxt, N'ц,ч,ф', 'ts,ch,q')?
you can wrap each character with another replace, however it could be quiet long. if you need to replace a lot of characters it is best to work with a mapping table.
0

I would recommend to define function parameters with appropriate length

So,

CREATE FUNCTION convert_lat(@rawtxt nvarchar) -- Will accept 1 length default

It would be instead

CREATE FUNCTION convert_lat(@rawtxt nvarchar(255))

1 Comment

@Xass1on, this may fix your most immediate problem, but consider the answer from hkravitz as well. What it implies without really saying is that it doesn't seem to make sense for your function to contain a SELECT ... FROM Connection.dbo.Raw statement given that its only purpose appears to be to retrieve a string that you already have (in the @rawtxt parameter).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.