0

I have this simple code to define and call a UDF, which works when run in VS Code:

IF OBJECT_ID(N'fn_get_date', N'FN') IS NOT NULL
    DROP FUNCTION fn_get_date
;
GO
CREATE FUNCTION fn_get_date ()
RETURNS DATE
BEGIN
    RETURN CAST(GETDATE() AS DATE);
END;
GO

SELECT dbo.fn_get_date() 'Test';

But putting it into an Excel file throws this error:

enter image description here

(Transcription: Unable to connect We encountered an error while trying to connect. Details: "Microsoft SQL: Incorrect syntax near 'GO'. 'CREATE FUNCTION' must be the first statement in a query batch. A RETURN statement with a return value cannot be used in this context.")

What might be causing this, assuming it's even possible to do this somehow?

  • `GO` is *not* a Transact-SQL operator, it's a utility statement recognised by tools like SSMS, ADS, and `sqlcmd` as a batch seperator; you can't just dump it into an application's code. You need to separate the batches yourself. – Thom A Jan 20 '23 at 17:46
  • @Larnu Ah, I had no idea about the distinction. Thanks, I'll look into it! – davidfjdkslfs Jan 20 '23 at 17:56
  • @Larnu In that case, would you know if there was a way to run multiple consecutive batches with Excel queries? – davidfjdkslfs Jan 20 '23 at 18:16
  • There's an example in that duplicate; check the second answer. – Thom A Jan 20 '23 at 18:20

0 Answers0