I am trying to create an SQL function that checks if a parameter starts with a specific term or contains but does not start with it.
Im accepting the following:
@fieldName is actually the name of the table (judging by your attempt to use).@searchterm is the term you are looking forData - column in the @fieldName table
If any of the above rules is incorrect, this answer is useless.
You will need to use dynamic sql, since the table in the selected query cannot be parameterized. You will need two different versions of dynamic sql that you want to check for "starts with" and more general "contains". To determine the result of the call, you need an output variable from dynamic sql.
INT is said to represent a complete excess in size. If you have only 2 states (which I doubt), you want BIT , if you have 3 states (as I suspect), you want TINYINT . I will stick with int in order to stay close to your original example, but consider changing.
CREATE FUNCTION [dbo].[fnGetRelevance] ( @fieldName nvarchar(50), @searchTerm nvarchar(50) ) RETURNS INT AS BEGIN DECLARE @startsWithResult INT, @containsResult INT DECLARE @startsWithSQL NVARCHAR(MAX) = N'SELECT @result=1 FROM ' + @fieldName + ' WHERE Data LIKE '' + @searchTerm + '%''' DECLARE @containsSQL NVARCHAR(MAX) = N'SELECT @result=1 FROM ' + @fieldName + ' WHERE Data LIKE ''%' + @searchTerm + '%''' EXEC sp_ExecuteSQL @startsWithSQL, N'@result int output', @result = @startsWithResult OUTPUT IF @startsWithResult = 1 RETURN 0 EXEC sp_ExecuteSQL @containsSQL, N'@result int output', @result = @containsResult OUTPUT IF @containsResult = 1 RETURN 1 END
source share