mandag den 28. december 2015

SQL Print Variable message in console




Declare @SumVal int;
Select @SumVal=Sum(Amount) From Expense; 
Print 'OMG' + @SumVal;


http://stackoverflow.com/questions/1943892/sql-server-print-select-print-a-select-query-result

onsdag den 23. december 2015

SQL to run on specific date time

http://www.sqlservercurry.com/2010/10/execute-t-sql-code-only-on-certain-days.html



I always clean up my databases manually on Sundays. But at times, if need be, I clean it up on other days as well. However I never do it on Saturdays, since the traffic is usually the most on that day.
So here’s a simple tip using IF-ELSE to prevent my T-SQL code from running on Saturday’s, even if I run the code manually
IF DATEPART(dw,GETDATE())<> 7  -- 7 is Saturday, 1 is SundayBEGIN
    -- YOUR T-SQL Code Comes Here   
     SELECT GETDATE()
     RETURN
END
ELSE
BEGIN
    PRINT '*** Sorry This Code will Not Execute on Saturdays'END
OUTPUT
image

tirsdag den 22. december 2015

Case Qhen instead of If else Null

CASE WHEN B.[STAT] IS NULL THEN (C.[EVENT DATE]+10)   -- Type DATETIME
     ELSE '-'                                         -- Type VARCHAR
     END AS [DATE]

SQL Scalar-Valued Function MSSQL for Business Logics

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @Input

    SET @Work = REPLACE(@Work, 'www.', '')
    SET @Work = REPLACE(@Work, '.com', '')

    RETURN @work
END
and then use:
SELECT ID, dbo.StripWWWandCom (WebsiteName)
FROM dbo.YourTable .....




CREATE FUNCTION dbo.RAGconvertion (@input NVARCHAR(250))
RETURNS Nvarchar(250)
AS BEGIN
    DECLARE @RAGint INT --Nvarchar(250)

    SET @RAGint = 
 CASE @Input
  WHEN 'Green' THEN '3'
  WHEN 'Amber' THEN '2'
  WHEN 'Red' THEN '1'
  WHEN '[Please Choose]' THEN '0'
  ELSE '0'
 END
    --SET @Work = REPLACE(@Work, 'www.', '')
    --SET @Work = REPLACE(@Work, '.com', '')

    RETURN @RAGint
END