Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

IF Function exists THEN run a query on the function - causing inconsistent results

$
0
0

I have some code that checks the existence of a Function. IF the function exists, THEN the function in used in the WHERE clause of a SELECT. IF the Function does not exists, THEN does something ELSE that does not reference the function. I have several DBs that do not have the function. One runs the code just fine, the other give me a syntax error on the code where the functino is used in the WHERE clause of a SELECT.

1) why are the two databases - which both do not have the function - give different results. One runs the code, one gives a syntax error.

2) how are you suppose to ask if a function exists prior to using the function, without giving a syntax error

This is the code where is run against one DB I get 'function does not exist'. run against another db, where the function does not exist it returns Message -Msg 102, Level 15, State 1, Line 8. Incorrect syntax near '('.

IF EXISTS(SELECT * FROM sys.objects WHERE name = 'fn_abc' AND type = 'IF')
	BEGIN
	print 'function exists'
	DECLARE db_cursor CURSOR FOR
		SELECT [Name]
			FROM  fn_abc(DB_NAME())
			ORDER BY 1
	END
else
	begin
	print 'function does not exist'
	end	


Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>