Is it possible to create a function in SQL server to act as clause e.g. Where or Limit I've found a simple way to mimic the limit clause is SQL server by using 

SELECT * FROM customers 
OFFSET 22
ROWS FETCH NEXT 5 ROWS ONLY


I'd like to replace those two line with

LIMIT(22, 5)
e.g.

SELECT * FROM customers
LIMIT(22, 5)
No, there are no macros in T-SQL to make that syntax look simpler (and non-standard!) or to perform inline substitution, at least in a native non-dynamic query. You do know that you can parameterize it, though, right?

ORDER BY &lt;need an ORDER BY&gt;
  OFFSET ((@PageNumber-1)*@PageSize) ROWS 
  FETCH NEXT (@PageSize) ROWS ONLY;


This way you are always adding the OFFSET clause but you can do it in a very standard way and not really have to look at it during everyday coding.

I suppose you could do what you want if you're okay with building your query using dynamic SQL, for example you could create a function like this:

CREATE FUNCTION dbo.Limit(@pn VARCHAR(12), @ps VARCHAR(12))
RETURNS NVARCHAR(255)
WITH SCHEMABINDING
AS
BEGIN
  RETURN (N' OFFSET ' + @pn + ' ROWS FETCH NEXT ' + @ps + ' ROWS ONLY');
END


Then you could call it like this:

DECLARE @sql NVARCHAR(MAX) = N'SELECT ... ORDER BY ...' + dbo.Limit(22,5);

PRINT @sql;


This looks kind of like what you typed in your sample, but I don't think it's what you really meant (or should want), unless you already have other reasons (e.g. wildly varying order by parameters or search filters) to use dynamic SQL anyway... still, this obfuscation and simplification doesn't help anybody learn SQL Server-specific syntax, and makes it harder for those people to write this stuff when they can't use the function. I don't think this is the type of "optimization" you should be spending a whole lot of effort on. You type these queries once, and when someone does learn the actual syntax, it is hard to justify using "shortcuts" that might not be any easier to remember in the long run (and can be harder to maintain if, for example, they need to made more flexible later).