Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

sql server - passando constantes sem aspas para funções como DATEPART faz


Você não pode realmente restringir a entrada de uma UDF a um pequeno conjunto de valores (até onde eu sei).

Eu recomendaria criar uma tabe para seus valores enumerados - algo assim:
CREATE TABLE MyEnumTable (DatePartID tinyint, DatePartValue char(2))
GO
INSERT MyEnumTable(DatePartID, DatePartValue)
SELECT 1, 'yy'
UNION
SELECT 2, 'mm'
UNION
SELECT 3, 'dd'
UNION
SELECT 4, 'hh'
GO

CREATE FUNCTION MyDatePart(@IntervalType tinyint)
RETURNS varchar(255)
AS
BEGIN
IF NOT EXISTS (SELECT * FROM MyEnumTable WHERE DatePartID = @IntervalType)
   RETURN 'Invalid IntervalType'

--Do your stuff
DECLARE @DatePartvalue char(2)
SELECT  @DatePartValue = DatePartValue
FROM    MyEnumTable
WHERE   DatePartID = @IntervalType

RETURN @DatePartValue
END

GO

--Check it out
SELECT dbo.MyDatePart(3), dbo.MyDatePart(12)

Claro, meu exemplo é simplificado demais, mas você entendeu.

Além disso, considere tornar a função uma função com valor de tabela por motivos de desempenho, se estiver planejando usar o udf em instruções set. Eu escrevi sobre as implicações de desempenho de vários tipos de função aqui:

http://thehobt.blogspot.com/2009 /02/scalar-functions-vs-table-value.html