MS-SQL etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
MS-SQL etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

SQL Query that search all column names based on criteria

While browsing the SQL Server newsgroups, every once in a while, I see a request for a script that can search all the columns of all the tables in a given database for a specific keyword. I never took such posts seriously. But then recently, one of my network administrators was troubleshooting a problem with Microsoft Operations Manager (MOM). MOM uses SQL Server for storing all the computer, alert and performance related information. He narrowed the problem down to something specific, and needed a script that can search all the MOM tables for a specific string. I had no such script handy at that time, so we ended up searching manually.


That's when I really felt the need for such a script and came up with this stored procedure "SearchAllTables". It accepts a search string as input parameter, goes and searches all char, varchar, nchar, nvarchar columns of all tables (only user created tables. System tables are excluded), owned by all users in the current database. Feel free to extend this procedure to search other datatypes.

The output of this stored procedure contains two columns:

- 1) The table name and column name in which the search string was found
- 2) The actual content/value of the column (Only the first 3630 characters are displayed)

Here's a word of caution, before you go ahead and run this procedure. Though this procedure is quite quick on smaller databases, it could take hours to complete, on a large database with too many character columns and a huge number of rows. So, if you are trying to run it on a large database, be prepared to wait (I did use the locking hint NOLOCK to reduce any locking). It is efficient to use Full-Text search feature for free text searching, but it doesn't make sense for this type of ad-hoc requirements.

Create this procedure in the required database and here is how you run it:

--To search all columns of all tables in Pubs database for the keyword "Computer"
EXEC SearchAllTables 'Serkan SONMEZ'
GO




CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)

WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)

IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END

SELECT ColumnName, ColumnValue FROM #Results
END

Cannot resolve the collation conflict between "Latin1_General_CI_AI" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.

Problem:

select name from sysusers where name not in ( select name from master..syslogins )

Microsoft SQL Server 2005 - 9.00.1399.06 (X64)
Oct 14 2005 00:35:21
Copyright (c) 1988-2005 Microsoft Corporation
Standard Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)
(1 row(s) affected)

Msg 468, Level 16, State 9, Line 1
Cannot resolve the collation conflict between "Latin1_General_CI_AI" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.


Resolution:

This is because your master is in a different collation than your user database.
Try adding the COLLATE to your query.

select name from sysusers where name not in ( select name COLLATE Latin1_General_CI_AI from master..syslogins )

SQL SERVER - Fix : Msg 15151, Level 16, State 1, Line 3 Cannot drop the login ‘test’, because it does not exist or you do not have permission

I got following error when I was trying to delete user ‘test’ with ‘SA’ login. I was little surprised but then I tried to delete with the windows authenticated systemadmin account. Once again I got the same error.

Msg 15151, Level 16, State 1, Line 3Cannot drop the login ‘test’, because it does not exist or you do not have permission.
The reason I was surprised that I was systemadmin and I should be allowed to delete the login. I am including the script which I used to delete the account here.

IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N’Test’)
DROP LOGIN [Test]

Fix/Workaround/Solution:
I finally found out that error was misleading. I had another session open in SQL Server Management Studio with username ‘test’ and it was preventing me to drop the user. Once I closed that open session I was successfully able to delete the user using above script.
In Normal Case:Following error usually show up when user is logged in, which I did not get it.

Msg 15434, Level 16, State 1, Line 3
Could not drop login ‘test’ as the user is currently logged in.

However, when I tried to re-create scenario I got above error. I want to share this experience with users and want to know if they have ever faced this scenario.

Msg 4621, Level 16, State 10, Line 1 Permissions at the server scope can only be granted when the current database is master



ERROR

Msg 4621, Level 16, State 10, Line 1
Permissions at the server scope can only be granted when the current database is master







Fix/Workaround/Solution:

If you look at the database in use is AdventureWorks and when any server level permission has to be granted the database in context should be of master database. Change the database used to master and it should fix the error.



Reference : Pinal Dave (http://blog.sqlauthority.com/)

The FORMAT() Function

The FORMAT() function is used to format how a field is to be displayed.


SQL FORMAT() Syntax
SELECT FORMAT(column_name,format) FROM table_name
Parameter
Description
column_name
Required. The field to be formatted.
format
Required. Specifies the format.


SQL FORMAT() Example
We have the following "Products" table:
Prod_Id
ProductName
Unit
UnitPrice
1
Jarlsberg
1000 g
10.45
2
Mascarpone
1000 g
32.56
3
Gorgonzola
1000 g
15.67
Now we want to display the products and prices per today's date (with today's date displayed in the following format "YYYY-MM-DD").
We use the following SELECT statement:
SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDateFROM Products
The result-set will look like this:
ProductName
UnitPrice
PerDate
Jarlsberg
10.45
2008-10-07
Mascarpone
32.56
2008-10-07
Gorgonzola
15.67
2008-10-07

How to Block SQL Injection Hackers with ASP Validation

Protect your database-driven ASP website from hacker attacks with powerful input validation. This will slow down hackers who use methods like SQL injection attacks and XSS (cross-site scripting) via the URL querystring and form inputs. These methods are simple enough that you can do it yourself with only basic coding knowledge.
Step 1
The first goal of a hacker is to repeatedly try to break a website, causing it to display a variety of valuable errors that give away private database details. In this way, he can gain insight into the structure of the database and ultimately create a map or footprint of all its tables and columns. The second goal of the hacker is to actually manipulate the database by executing scripts in malicious ways. With control over the database, the hacker may possibly steal credit card numbers, erase data or infect it with viruses, among other nasty things. In essence, the URL querystring and textbox are the two backdoors into a database. Getting errors and manipulating the backdoors are the two methods used by hackers to ultimately destroy a database. For more details, see my companion article in the resources section or at http://www.ehow.com/how_4434719_protect-website-hacker-attacks.html .
Step 2
Block input containing malicious code.The number one way to block a hacker from manipulating the URL querstrying and textboxes is to block their input. But, how do you determine who they are, what they will input and whether or not it is safe? Unfortunately, you cannot know. So, you must assume that all user input could be potentially dangerous. A common saying in the programming world is that ALL INPUT IS EVIL. Thus, it must be treated with caution. Everything from everybody should be checked every time to ensure dangerous code does not slip in. This is accomplished by checking all input that is submitted via a querystring or form and then rejecting or removing unsafe characters before it ever reaches the database. If this sounds like a lot of trouble, you are right. But, it is the price we pay to protect our websites and databases from the wrath of hackers. It is your responsibility as the webmaster to ensure that only clean, safe input is allowed to enter your database.
Step 3
Input validation.To check if the input entered into the URL querystring or textbox is safe, we can use input validation rules. In other words, using ASP code on a web page can validate the input collected from the querystring or form to make sure it contains only safe characters. Once the input is deemed safe, it can be stored in a new variable, inserted into the SQL string and sent to the database.
Step 4
The wash and rinse cycle.Input validation should be a two-part process, like a wash and rinse cycle. We want to thoroughly clean all input by first checking for safe characters and second by checking for bad strings. See the resources at the end of this article for a more in depth discussion on this method.
Step 5
Only allow safe characters.Part one of the validation process is to reject all input unless it contains safe characters. This is the strictest and most effective form of input validation. It only allows input that is known to be good. Essentially, letters and numbers can be trusted. Special characters are the real culprits which give hackers their power and should be avoided. This extreme measure may not be feasible for all types of input, but try to restrict as many special characters as possible. See the resources at the end of this article for a more in depth discussion on this method.
Step6
Following is an ASP example that could be used for a login or search input field. It allows only a-z, A-Z, 0-9 and an apostrophe, hyphen and space. You can modify the function to include characters as you see fit. %'validation allows only good charactersfunction valGoodChars(input)good_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'- "valGoodChars = truefor i = 1 to len(input)c = mid(input, i, 1)if (InStr(good_chars, c) = 0) thenvalGoodChars = falseexit functionend ifnextend function'collect the form inputsearchInput = Request.QueryString("searchKeyword")‘if an unsafe input is entered the user is asked to try againif (not valGoodChars(searchInput)) thenresponse.redirect("sorryTryAgain.asp")end if%>Remember to use a solution that best fits your website or consult a professional.
Step 7
Part two of the validation process is to reject all input if it contains bad strings. After you have collected good input with the method above, you should check it again for input that is known to be bad. Dangerous things could happen if the good character function allowed an apostrophe and hyphen, or other letter combinations like SCRIPT, SELECT, UPDATE, DELETE, etc. That is why the bad string function should be used in conjunction with the good character function. See the resources at the end of this article for a more in depth discussion on this method.
Step 8
Following is an ASP example that rejects bad characters and should be used after checking for good characters. Bad characters could include a pair of hyphens and the word script, among other things. You can modify the function to include the bad strings as you see fit. |%'validation disallows bad stringsfunction valBadStrings( input )bad_strings = Array( "--", "script" )for each i in bad_stringsif ( InStr( input, i ) <> 0 ) thenvalBadStrings = falseexit functionend ifnextvalBadStrings = trueend function‘if an unsafe input is entered the user is asked to try againif (not valBadStrings(searchInput)) thenresponse.redirect("sorryTryAgain.asp")end if%>Remember to use a solution that best fits your website or consult a professional.
Step 9
Safely query the database.Now that the input has been laundered through the good and bad functions, it is ready to be inserted into the SQL query and executed by the database. Following is sample ASP code that inserts the searchInput. queries the database for a match, then displays the results.<%'check the database for a matchSet myRecordSet = Connect.Execute ("SELECT * FROM dbo.myTable WHERE myColumn LIKE '%" & searchInput & "%'")'display the resultsif myRecordSet.EOF then'display message no results foundelse'display resultsend if end if%>By validating the input before sending it to the database you have greatly reduced the risk of your database being compromised by hackers.
Step 10
Filter characters.Another method that can be used in conjunction with the above two functions, but is considered to be very weak when used alone, is to sanitize the input by filtering or escaping. A well-known threat is the single quote or apostrophe because it breaks the SQL statement. Following is an ASP example that renders the single quote harmless, by replacing it with two single quotes.'doubleup single quotesnewSafeString = replace(searchInput, "'", "''")Other variations for the replace function include stripping out the script tag and replacing it with a space. Or, filter out characters such as the dollar sign $ quotation mark “ semi-colon ; and apostrophe ‘ the left and right angle brackets <> the left and right parentheses ( ) the pound sign # and the ampersand &. Or convert these characters to their HTML entities.Remember to use a solution that best fits your website or consult a professional.
Step 11
If you would like to pursue more advanced security techniques, please see the resources at the end of this article. Topics discussed include, password policies, buffer overrun, creative table and column names, table name aliases, set and check data types, .bak files, stored procedures with parameters, and log files.

Find SQL Servers From Local Network - (By Command Line)

Go to command prompt and type in “osql -L” or “sqlcmd -L”.


Or
SQLCMD -L > c:\servers_filename.txt
Copy to servers_filename.txt

MS-SQL: How to enable the use of 'Ad Hoc Distributed Queries' by using sp_configure (OpenRowset)

If you are planning to use OpenRowset queries in order to connet to remote database servers or if you have already implemented OpenRowset queries as a solution to remote connections as an alternative tp linked servers in Microsoft SQL Server 2005, you should first configure the database instance to enable Ad Hoc Distributed Queries in the installed SQL Server database instance where the Ad Hoc query will run.



We should connect to the related SQL Server as an administrator and open a new query window.



To set 'show advanced options' run_value equal to 1 or to enable it, run


sp_configure 'show advanced options', 1

reconfigure


The return message from the above sql statements for a successful run is as;


Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.


After Advanced Options is enabled, you can again run sp_configure t-sql command and in the returned list of configuration settings, go to row where name is 'Ad Hoc Distributed Queries' and control its run_value.

If 'Ad Hoc Distributed Queries' is turned off for considering server security run_value should be "0"But since we want to enable 'Ad Hoc Distributed Queries' component in order to run 'OpenRowset/OpenDatasource' sql statements, we should set the run_value to "1"
The below sql code is a sample how you can enable a SQL Server configuration parameter.


sp_configure 'Ad Hoc Distributed Queries', 1

reconfigure


The returned message is :
Configuration option 'Ad Hoc Distributed Queries' changed from 0 to 1. Run the RECONFIGURE statement to install.

Now you can see the run_value is set to 1 if you run the "sp_configure" command and control for the "Ad Hoc Distributed Queries" row.




Now you can run your OpenRowset queries successfully from your SQL Server 2005 or SQL Server 2008 (Katmai) databases.

Unity : Firma ve dönemleri listeleyen sorgu

Unity'de kullanılan dönem ve firmaları listelemek için aşağıdaki sorguyu çalıştırabilirsiniz.

SELECT FIRM.NR AS FIRMA_NO,FIRM.NAME AS FIRMA_ADI,PERIOD.NR AS DONEM_NO FROM L_CAPIFIRM AS FIRM INNER JOIN L_CAPIPERIOD AS PERIOD ON FIRM.NR=PERIOD.FIRMNR ORDER BY FIRMA_NO,DONEM_NO

Unity : 2009 Aylık BS formu sorgusu

SELECT C.CODE AS CARI, C.DEFINITION_ AS ACIKLAMA, C.TAXNR AS VERGI_NO, C.TAXOFFICE AS VERGI_DAIRESI, C.TELNRS1,
SUM(INV.NETTOTAL - INV.TOTALVAT) AS TUTAR, COUNT(INV.LOGICALREF) AS BELGE_SAYISI,MONTH(DATE_) AS AY
FROM dbo.LG_444_01_INVOICE INV INNER JOIN
dbo.LG_444_CLCARD C ON INV.CLIENTREF = C.LOGICALREF
WHERE (INV.TRCODE IN (6, 7, 8, 9,14)) AND (INV.CANCELLED = 0) AND INV.DECPRDIFF=0
GROUP BY C.CODE, C.DEFINITION_, C.TAXNR, C.TAXOFFICE, C.TELNRS1,MONTH(DATE_)
HAVING (SUM(INV.NETTOTAL - INV.TOTALVAT) >= 8000)

Unity : 2009 Aylık BA formu sorgusu

SELECT C.CODE CARI
, C.DEFINITION_ ACIKLAMA
,C.TAXNR AS VERGI_NO
,C.TAXOFFICE AS VERGI_DAIRESI
,C.TELNRS1
, SUM(INV.nettotal-INV.totalvat) AS TUTAR
,COUNT(INV.LOGICALREF) AS BELGE_SAYISI
,MONTH(DATE_) AS AY

FROM LG_444_01_INVOICE INV, LG_444_CLCARD C
WHERE INV.CLIENTREF =C.LOGICALREF
and ((INV.TRCODE IN (1,2,3,4)) OR
(INV.TRCODE = 14 AND INV.DECPRDIFF=1))

AND INV.CANCELLED=0
group BY C.CODE,C.DEFINITION_,C.TAXNR,C.TAXOFFICE,C.TELNRS1,MONTH(DATE_)
HAVING SUM(INV.nettotal-INV.totalvat)>=8000

Malzeme Kartı özelliklerine otomatik kayıt açmak. (LG_XXX_CHARASGN)

Unity'de malzeme kartında bulunan "Malzeme Özellikleri" tabına otomatik olarak kayıt eklemek için aşağıdaki cursor'u kullanabilirsiniz.





Kullanımı:



EXEC [dbo].[SP_CHARASGN_INSERT] '508' ,'822096031A0330640000208'

Açıklaması:
İlk parametre firma numarası, ikinci parametre ise malzeme kodudur.


SQL Kodu:
CREATE PROCEDURE [dbo].[SP_CHARASGN_INSERT]

@FIRMNR VARCHAR(5),
@NEWCODE VARCHAR(30)
AS
EXEC(
'DECLARE
@MAXREF INT,
@MAXREF2 INT,
@MAXREF3 INT,
@LOGICALREF INT,
@LINENR INT,
@CHARVALREF INT,
@CHARCODEREF INT,
@CODE VARCHAR(50),
@CHARVAL VARCHAR(50),
@SPECODE VARCHAR(50),
@CYPHCODE VARCHAR(50)

DECLARE CARI CURSOR FOR

SELECT LOGICALREF,CODE FROM LG_' + @FIRMNR + '_ITEMS (NOLOCK) WHERE LOGICALREF NOT IN (
SELECT ITEMREF FROM LG_' + @FIRMNR + '_CHARASGN) AND CARDTYPE NOT IN (20,22) AND ACTIVE =0 AND CODE =''' + @NEWCODE + '''
ORDER BY CODE

OPEN CARI
FETCH NEXT FROM CARI
INTO @LOGICALREF,@CODE
WHILE @@FETCH_STATUS = 0
BEGIN
SET @LINENR=1
WHILE @LINENR<>5
BEGIN
SELECT @MAXREF=ISNULL(MAX(LASTLREF),0) + 1 FROM LG_' + @FIRMNR + '_CHARASGNSEQ WHERE ID=1
UPDATE LG_' + @FIRMNR + '_CHARASGNSEQ SET LASTLREF=@MAXREF WHERE ID=1
SET @CHARCODEREF = @LINENR + 1
IF @LINENR=1 --BRAND
BEGIN
SELECT @CHARVAL=NAME FROM [10.0.0.26].[BURSA1].[DBO].LG_BRAND WHERE CODE=SUBSTRING(@CODE,4,3)
END
IF @LINENR=2 --TICKET
BEGIN
SELECT @CHARVAL=NAME FROM [10.0.0.26].[BURSA1].[DBO].LG_TICKETNO WHERE CODE=SUBSTRING(@CODE,7,3)
END
IF @LINENR=3 --METER
BEGIN
SELECT @CHARVAL=NAME FROM [10.0.0.26].[BURSA1].[DBO].LG_METRAJ WHERE CODE=SUBSTRING(@CODE,10,4)
END
IF @LINENR=4 --COLOR
BEGIN
SET @CHARVAL=SUBSTRING(@CODE,19,5)
END
SET @CHARVALREF = 0

SELECT @CHARVALREF=LOGICALREF FROM LG_' + @FIRMNR + '_CHARVAL WHERE CHARCODEREF=@CHARCODEREF AND CODE =@CHARVAL
IF @CHARVALREF = 0
BEGIN
SELECT @MAXREF2=ISNULL(MAX(LASTLREF),0) + 1 FROM LG_' + @FIRMNR + '_CHARVALSEQ WHERE ID=1
UPDATE LG_' + @FIRMNR + '_CHARVALSEQ SET LASTLREF=@MAXREF2 WHERE ID=1

SELECT @MAXREF3=ISNULL(MAX(VALNO),0) + 1 FROM LG_' + @FIRMNR + '_CHARVAL WHERE CHARCODEREF=@CHARCODEREF
INSERT INTO LG_' + @FIRMNR + '_CHARVAL (LOGICALREF,CHARCODEREF,VALNO,CODE,NAME)
VALUES (@MAXREF2,@CHARCODEREF,@MAXREF3,@CHARVAL,@CHARVAL)
SELECT @CHARVALREF=LOGICALREF FROM LG_' + @FIRMNR + '_CHARVAL WHERE CHARCODEREF=@CHARCODEREF AND CODE =@CHARVAL
END

INSERT INTO LG_' + @FIRMNR + '_CHARASGN (LOGICALREF,ITEMREF,CHARCODEREF,CHARVALREF,LINENR,MATRIXLOC,PRIORITY)
VALUES (@MAXREF,@LOGICALREF,@CHARCODEREF,@CHARVALREF,@LINENR,0,0)
SET @LINENR = @LINENR + 1
END
FETCH NEXT FROM CARI
INTO @LOGICALREF,@CODE
END
CLOSE CARI
DEALLOCATE CARI')

Enable Ole automation for MS SQL


The following steps for "Enable Ole automation",


start ->


programs ->


MS sql 2005 ->


configuration tools ->


surface area configuration ->


Surface area conf for features ->



Ole automation ->


select the Enable check box and saved


SQL SERVER - Fix : Error : Server: Msg 544, Level 16, State 1, Line 1 Cannot insert explicit value for identity column in table

Server: Msg 544, Level 16, State 1, Line 1Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF.

This error message appears when you try to insert a value into a column for which the IDENTITY property was declared, but without having set the IDENTITY_INSERT setting for the table to ON.

Fix/WorkAround/Solution:
--Turn Identity Insert ON so records can be inserted in the Identity Column
SET IDENTITY_INSERT [dbo].[TableName] ON
GO
INSERT INTO [dbo].[TableName] ( [ID], [Name] )VALUES ( 2, 'InsertName')
GO
--Turn Identity Insert OFF
SET IDENTITY_INSERT [dbo].[TableName] OFF
GO


Setting the IDENTITY_INSERT to ON allows explicit values to be inserted into the identity column of a table. Execute permissions for the SET IDENTITY_INSERT default to the sysadmin fixed server role and the db_owner and db_ddladmin fixed database roles, and the object owner.

Find Weekdays Between Two Dates (SQL Function-UDF)

Following user defined function returns number of weekdays between two dates specified. This function excludes the dates which are passed as input params. It excludes Saturday and Sunday as they are weekends.
CREATE FUNCTION dbo.spDBA_GetWeekDays( @StartDate datetime,@EndDate datetime )RETURNS INT AS
BEGIN
DECLARE @WorkDays INT,
@FirstPart INT
DECLARE @FirstNum INT, @TotalDays INT
DECLARE @LastNum INT, @LastPart INT
IF (DATEDIFF(DAY, @StartDate, @EndDate) 0)
THEN @LastPart - 1ELSE 0
END
SELECT @WorkDays = @WorkDays * 5 + @FirstNum + @LastNum
END
RETURN ( @WorkDays )END
GO

This function can be used as
SELECT dbo.spDBA_GetWeekDays (‘10/10/2008′, ‘11/22/2008′)
GO

Find day of the Current Week

Very Simple Script which find Day of the Current Week;


SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)
Result:
2009-02-09 00:00:00.000 --Day(0) --Monday


SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 4)
Result:
2009-02-13 00:00:00.000 --Day (4) --Friday

Get Number of Days in Month (SQL Function-UDF)

Following User Defined Function (UDF) returns the numbers of days in month. It is very simple yet very powerful and full proof UDF.

CREATE FUNCTION [dbo].[udf_GetNumDaysInMonth]
( @myDateTime DATETIME )RETURNS INT AS
BEGIN
DECLARE @rtDate INT
SET @rtDate = CASE WHEN MONTH(@myDateTime) IN (1, 3, 5, 7, 8, 10, 12) THEN 31
WHEN MONTH(@myDateTime) IN (4, 6, 9, 11) THEN 30
ELSE CASE WHEN (YEAR(@myDateTime) % 4 = 0 AND YEAR(@myDateTime) % 100 != 0) OR (YEAR (@myDateTime) % 400 = 0) THEN 29
ELSE 28 END
END
RETURN @rtDate
END
GO




Run following script in Query Editor:

SELECT dbo.udf_GetNumDaysInMonth(GETDATE()) -- Today = 13.02.2009

Result :

28

Few Useful DateTime Functions to Find Specific Dates

Few Useful DateTime Functions to Find Specific Dates functions.
—-Today
SELECT GETDATE() ‘Today’
—-Yesterday
SELECT DATEADD(d,-1,GETDATE()) ‘Yesterday’
—-First Day of Current Week
SELECT DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0) ‘First Day of Current Week’
—-Last Day of Current Week
SELECT DATEADD(wk,DATEDIFF(wk,0,GETDATE()),6) ‘Last Day of Current Week’
—-First Day of Last Week
SELECT DATEADD(wk,DATEDIFF(wk,7,GETDATE()),0) ‘First Day of Last Week’
—-Last Day of Last Week
SELECT DATEADD(wk,DATEDIFF(wk,7,GETDATE()),6) ‘Last Day of Last Week’
—-First Day of Current Month
SELECT DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0) ‘First Day of Current Month’
—-Last Day of Current Month
SELECT DATEADD(ms,- 3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,GETDATE())+1,0))) ‘Last Day of Current Month’
—-First Day of Last Month
SELECT DATEADD(mm,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)) ‘First Day of Last Month’
—-Last Day of Last Month
SELECT DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))) ‘Last Day of Last Month’
—-First Day of Current Year
SELECT DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0) ‘First Day of Current Year’
—-Last Day of Current Year
SELECT DATEADD(ms,-3,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0))) ‘Last Day of Current Year’
—-First Day of Last Year
SELECT DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)) ‘First Day of Last Year’
—-Last Day of Last Year
SELECT DATEADD(ms,-3,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))) ‘Last Day of Last Year’

How to create and use a sample sql cursor and cursor code

Here is a sample sql cursor code created for looping through a list of records as a result of a select query, which enables the sql developer to execute a stored procedure for each row in the cursor which use the values fetched by the cursor as the input arguments. The sample cursor is developed on a SQL Server and is a sample for sql server cursor. The sql codes may use t-sql codes so the sample may have differences than a typical pl sql cursor or an oracle cursor.

The sample sql cursor codes below illustrates a process of merging dublicate customer records kept in an application database. Assume that the dublicate customers list and relation among the duclicate customer records are inserted into and kept in a table named DublicateCustomers which is simply formed of columns MasterCustomerId, DublicateCustomerId and some other columns like MergeDate, IsMerged, MergedByUserId, InsertedDate, InsertedByUserId, etc which are used during processing some details and useful in the reporting of the dublicate record merge process results.



The list of the original customer records and the dublicate customer records can be selected by the sql select query below:

SELECT MasterCustomerId, DublicateCustomerIdFROM DublicateCustomers WHERE IsMerged = 0

You can either create a temporary table to keep the result set in order to use your initial set of records in the next steps of your process or you can just use the above sql query to supply your records set to feed the cursor we will create.
Here with the variable declarations we will set column values we fetch with the cursor to the variables.


DECLARE @MergeDate Datetime
DECLARE @MasterId Int
DECLARE @DublicateId Int

Then the sql cursor definition or the cursor declaration code takes place.

DECLARE merge_cursor CURSOR FAST_FORWARD FOR
SELECT MasterCustomerId, DublicateCustomerId
FROM DublicateCustomers WHERE IsMerged = 0

During the cursor declararion you can set the cursor properties or the attributes of the cursor. Note that the sample cursor declaration uses the FAST_FORWARD key attribute in order to create a cursor with a high performance. Since FAST_FORWARD states that the cursor is FORWARD_ONLY and READ_ONLY the performance of the cursor is optimized.
The t-sql syntax of cursor declaration command DECLARE CURSOR is stated as below :

DECLARE cursor_name CURSOR [ LOCAL GLOBAL ] [ FORWARD_ONLY SCROLL ] [ STATIC KEYSET DYNAMIC FAST_FORWARD ] [ READ_ONLY SCROLL_LOCKS OPTIMISTIC ] [ TYPE_WARNING ] FOR select_statement [ FOR UPDATE [ OF column_name [ ,...n ] ] ]

You can find more on how to declare a cursor and cursor attributes in Books Online
With the call of the OPEN command the t-sql server cursor is opened and the cursor is populated with the data by the execution of the select query of the DECLARE CURSOR command.


OPEN merge_cursor

So the OPEN command runs or executes the "SELECT MasterCustomerId, DublicateCustomerId FROM DublicateCustomers WHERE IsMerged = 0"
select query defined in the DECLARE CURSOR definition command which is set after FOR key.

With the execution of this select query the cursor is populated with the rows or the data returned as a result set of the query.

The next step in using a cursor is fetching the rows from the populated cursor one by one.

FETCH NEXT FROM merge_cursor INTO @MasterId, @DublicateId
The syntax of the FETCH command is as follows
FETCH [ [ NEXT PRIOR FIRST LAST ABSOLUTE { n @nvar } RELATIVE { n @nvar } ] FROM ] { { [ GLOBAL ] cursor_name } @cursor_variable_name } [ INTO @variable_name [ ,...n ] ]

With the use of the NEXT, the FETCH NEXT command returns the row following the current row. If FETCH NEXT is called for the first time for a cursor, or we can say if it is called after the OPEN CURSOR command, then the first row in the returned result set is fetched or returned. The column values in the returned row can be set into variables with the INTO key and by giving the names of the variables as a comma seperated list after the INTO key.
So for our sample the first row in the return result set of the cursor is set into two variables named @MasterId and @DublicateId. Here one important point is the first column of the result set (column named MasterCustomerId) is set to first variable defined in the list which is the @MasterId variable. And the secod column named DublicateCustomerId is set to the second variable @DublicateId.
So the variable types must be carefully declared according to the column types of the selected rows.
After the FETCH command, you should always control the value of the @@FETCH_STATUS. This variable returns the status of the last cursor FETCH command in the current connection.
The possible return values of @@FETCH_STATUS are;
0
FETCH statement was successful
-1
FETCH statement failed or the row was beyond the result set
-2
Row fetched is missing
By always checking the @@FETCH_STATUS and controlling that it is value is equal to "0" we will have a new row fetched. When the fetched status is different than the "0" we can say that we have no more records are fetched. In short, the value of @@FETCH_STATUS variable is the controlling parameter of the loop we will use during processing all records or rows in the cursor.
In the body part of the WHILE statement the codes to process each row returned by the cursor takes place. This code block changes according to your reason to create and use a cursor. I placed an EXEC call for a sql stored procedure and an UPDATE sql statement here in order to show as a sample.
The most important thing to care for the inside codes of the WHILE code block is the last code statement FETCH NEXT command is recalled to get the next row from the return cursor data set.
After all the records are processed the @@FETCH_STATUS parameter returns -1, so the cursor can be now closed with the CLOSE CURSOR command. CLOSE CURSOR releases the current result set. And the DEALLOCATE CURSOR command releases the last cursor reference.
Here you can find the full sample sql cursor code used in this article for explaining the cursors in SQL Server.


DECLARE @MergeDate Datetime
DECLARE @MasterId Int
DECLARE @DublicateId Int
SELECT @MergeDate = GetDate()
DECLARE merge_cursor CURSOR FAST_FORWARD FOR
SELECT MasterCustomerId, DublicateCustomerId FROM DublicateCustomers WHERE IsMerged = 0
OPEN merge_cursor FETCH NEXT FROM merge_cursor
INTO @MasterId, @DublicateId
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC MergeDuplicateCustomers @MasterId, @DublicateId
UPDATE DublicateCustomersSETIsMerged = 1,MergeDate = @MergeDate
WHERE
MasterCustomerId = @MasterId ANDDublicateCustomerId = @DublicateId
FETCH NEXT FROM merge_cursor
INTO @MasterId, @DublicateId
END
CLOSE merge_cursor
DEALLOCATE merge_cursor

Query with transaction isolation level set to READ UNCOMMITTED fails with error 601

When a query runs with its transaction isolation level set to READ UNCOMMITTED, SQL Server 2000 aborts the query and returns the following error message:
Server:
Msg 601, Level 12, State 3, Line 14 Could not continue scan with NOLOCK due to data movement.
COUSE:
This behavior may occur when a row in a table is deleted between the time SQL Server reads the location of the row from an index and the time SQL Server fetches the row.

RESOLUTION:
Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the "Applies to" section.This problem was first corrected in Microsoft SQL Server 2000 Service Pack 4.

You can run the following query in Query Analyzer to dynamically turn on the trace flag:

DBCC TRACEON (9134, -1)

BlackListIP control on Serenity platform (.NET Core)

 In the Serenity platform, if you want to block IPs that belong to people you do not want to come from outside in the .net core web project,...