Sunday, April 21, 2013

Error: CREATE/ALTER PROCEDURE must be the first statement in a query batch

I had not come across this error before so was a new one for me. 

declare @cmd varchar(200)
set @cmd = 'sp_rename myproc1, myproc'
exec @cmd
GO

create procedure myproc (input_id int)
as
begin
  if input_id = 0
  begin
    print 'i am in begin block #2'
  end
end

The GO indicates end of batch or acts as a batch separator was missing from the script and as a result the error was generated. Once i added the GO statement, the script executed like a happy little monster....

Hope this helps....

Tuesday, April 16, 2013

DATEADD and DATEDIFF


I always try to remember these functions but for some reason end up going to MSDN to find the actual function name and syntax.

DATEADD (datepart , number , date )
select DATEADD (mm, 1, getdate())

DATEDIFF ( datepart , startdate , enddate )
select DATEDIFF (hh, getdate(), '2013-04-16 00:11:11.00')

Table below is from MSDN, just to you everyone an overview of possible option to use 
with these functions (along with any other DATE functions)

datepart abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Hope this helps and as always good is my friend....

Tuesday, April 9, 2013

Retrieve table structure over linked server

exec linkedserver.master.dbo.sp_executesql N'use mydb; exec sp_help order_details'

OR


exec linkedserver master.dbo.sp_executesql N'use mydb; SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ''order_details'''

Hope this helps....