Glenn
Glenn

Reputation: 156

Is there a way to create query specific functions in SQL Server 2008?

In an effort to adhere to the Dry Principle I have some code I feel could easily live in a function. I may need to reuse this code at some point in the future, I may not. Ideally I would have a function that lives just in this piece of code as it provides no benefit to the database as a whole and living inside any of the existing scheme's will create noise when trying to find meaningful and globally useful functions.

I have tried to write a script which uses typical syntax to create a function before my other code and drop the function at the end of the code. This is less than ideal because of potential collisions in the future, but an acceptable risk. Unfortunately I get an error:

'CREATE FUNCTION' must be the first statement in a query batch. 

Adding semi-colons before and after the statement unfortunately is not a quick fix. Is there no way to quickly to use functions without building them into the framework of the database?

Or am I asking the wrong question. Is there a way in one script to force separate batches?

Upvotes: 0

Views: 97

Answers (1)

paulsm4
paulsm4

Reputation: 121809

If you're truly running a "batch" (e.g. a set of T-SQL commands run in Query analyzer or ossql), then simply use "go". Your "create function" should work if it's the first line after a "go" - again, depending on your T-SQL interpreter. OSSQL: should work. An ADO connection in a VB6 program: definitely WON'T work.

Upvotes: 2

Related Questions