How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer If you’re not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables: var myname varchar2(20); exec :myname := ‘Tom’; SELECT * FROM Customers WHERE Name = :myname; In many tools (such as Toad and SQL Developer), omitting the var and exec … Read more

When would you use a table-valued function? [closed]

Table-valued functions are “just” parameterized views. This makes them extremely powerful for encapsulating logic that would otherwise be hidden behind an opaque stored procedure. Here’s an example: Inline Table-valued Function: create function dbo.GetClients ( @clientName nvarchar(max) = null ) returns table return ( select * from dbo.Clients as a where ((a.ClientName = @clientName) or a.ClientName … Read more

How to create a pivot query in sql server without aggregate function

SELECT * FROM ( SELECT [Period], [Account], [Value] FROM TableName ) AS source PIVOT ( MAX([Value]) FOR [Period] IN ([2000], [2001], [2002]) ) as pvt Another way, SELECT ACCOUNT, MAX(CASE WHEN Period = ‘2000’ THEN Value ELSE NULL END) [2000], MAX(CASE WHEN Period = ‘2001’ THEN Value ELSE NULL END) [2001], MAX(CASE WHEN Period = … Read more

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand From that article: DECLARE … Read more