# FUNÇÕES

* Uma função é uma sequência de comandos que executa alguma tarefa e que tem um nome. A sua principal finalidade é nos ajudar a organizar programas em pedaços que correspondam a como imaginamos uma solução do problema.

Exemplo de um Função Simples:

```sql
CREATE FUNCTION fnRetornaAno (@data DATETIME)
RETURNS int
AS
  BEGIN
  DECLARE @ano int
  SET @ano = YEAR(@data)

      RETURN @ano

END
```

* Chamada ou execução da função (não esqueça de usar o dbo. antes do nome da função)

```sql
SELECT dbo.fnRetornaAno(GETDATE())

SELECT dbo.fnRetornaAno(Clientes.ClienteNascimento) FROM dbo.Clientes
```

Exemplo de um Função que retorna uma tabela:

```sql
CREATE FUNCTION clientesApos(@dt datetime)
RETURNS TABLE
AS
RETURN (SELECT *
        FROM  Clientes
        WHERE ClienteNascimento >= @dt)

```

Exemplo de execução

```sql
SELECT * FROM CLIENTES 
INNER JOIN 
clientesApos('1980-01-01') AS FN
ON CLIENTES.CLIENTENASCIMENTO=FN.CLIENTENASCIMENTO
```

Exemplo de um Função com mais de um parâmetro de entrada:

```sql
CREATE FUNCTION DtsMinutos(@min int, @dti datetime, @dtf datetime)
RETURNS @tbl TABLE(dt datetime)
AS
BEGIN
    WHILE @dti <= @dtf
    BEGIN
      INSERT INTO @tbl(dt) VALUES (@dti)
      SET @dti = DATEADD(MINUTE,@min,@dti)
    END      
    RETURN
END
```

Exemplo de execução da função

```sql
select * from DtsMinutos(1,getdate(),getdate()+1)

```

Outros tipos de funções

<https://www.w3schools.com/sql/sql_ref_sqlserver.asp>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://rdornel.gitbook.io/material/linguagem-sql/funcoes.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
