Search


Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Monday, April 7, 2008

Using CAST and CONVERT with datetime data

SELECT
  GETDATE() AS UnconvertedDateTime,
  CAST(GETDATE() AS nvarchar(30)) AS UsingCast,
  CONVERT(nvarchar(30), GETDATE(), 126) AS UsingConvertTo_ISO8601  ;
GO

Here is the result set.

UnconvertedDateTime UsingCast UsingConvertTo_ISO8601

----------------------- ------------------------------ ------------------------------

2006-04-18 09:58:04.570 Apr 18 2006 9:58AM 2006-04-18T09:58:04.570

http://msdn2.microsoft.com/en-us/library/ms187928.aspx

ntext and varchar can't use operators: =, != , <, >

problem: The data types ntext and varchar are incompatible in the equal to operator. solution use LIKE or PATINDEX, for

Friday, April 4, 2008

Pattern Matching

pattern matching: • % (percent mark): This wildcard represents zero to many characters. For example, WHERE title LIKE '%C# 2008%' finds all book titles containing the text “C# 2008,” regardless of where in the title that text occurs—at the beginning, middle, or end. In this case, book titles such as “C# 2008: An Introduction,” “Accelerated C# 2008,” and “Beginning C# 2008 Databases” will be listed. • _ (underscore): A single underscore represents any single character. By using this wildcard character, you can be very specific in your search about the character length of the data you seek. For example, WHERE au_fname LIKE '_ean' finds all the first names that consist of four letters and that end with “ean” (Dean, Sean, and so on). WHERE au_fname LIKE 'a___n' finds all the first names that begin with “a” and end with “n” and have any other three characters in between, for example, allan, amman, aryan, and so on. • [ ] (square brackets): These specify any single character within the specified range, such as [a-f], or set, such as [abcdef] or even [adf]. For example, WHERE au_lname LIKE '[C-K]arsen' finds author last names ending with “arsen” and starting with any single character between “C” and “K,” such as Carsen, Darsen, Larsen, Karsen, and so on. • [^] (square brackets and caret): These specify any single character not within the specified range, such as [^a-f], or set, such as [^abcdef]. For example, WHERE au_lname LIKE 'de[^l]%' retrieves all author last names starting with “de,” but the following letter cannot be “l.”

Thursday, April 3, 2008

try catch in sql

TRY...CATCH (Transact-SQL) Syntax: BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH [ { sql_statement | statement_block } ] END CATCH [ ; ] http://msdn2.microsoft.com/en-us/library/ms175976.aspx

NVARCHAR versus VARCHAR

NVARCHAR versus VARCHAR

SQL Server provides both datatypes to store character information. For the most part the two datatypes are identical in how you would work with them within SQL Server or from an application. The difference is that nvarchar is used to store unicode data, which is used to store multilingual data in your database tables. Other languages have an extended set of character codes that need to be saved and this datatype allows for this extension. If your database will not be storing multilingual data you should use the varchar datatype instead. The reason for this is that nvarchar takes twice as much space as varchar, this is because of the need to store the extended character codes for other languages

How to merge 2 database

Use SQL server import and export Wizard: - go to database name on Object Explorer - right click on the database name - Task -> Export Data.. -> next -> choose source -> choose destenation - just follow the instruction ~

merging 2 tables each containing the same columns in sql

I have two tables, each containing the same columns: one containing 1000 rows and one with 800 rows. How can I create a third table which is a merge of the other two and ensuring there are no duplicates === Insert into table3 select * from table1 union select * from table2 === if there are no duplicate use: unionall

Wednesday, April 2, 2008

Unpacking Lists in a Table

problem example:
CREATE PROCEDURE get_product_names @ids varchar(50) AS
SELECT ProductID, ProductName
FROM   Northwind..Products
WHERE  ProductID IN (@ids)

above procedure will not work..

solution:

CREATE FUNCTION iter_charlist_to_tbl
                (@list      nvarchar(MAX),
                 @delimiter nchar(1) = N',')
     RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
                         str     varchar(4000)      NOT NULL,
                         nstr    nvarchar(2000)     NOT NULL) AS

BEGIN
  DECLARE @endpos   int,
          @startpos int,
          @textpos  int,
          @chunklen smallint,
          @tmpstr   nvarchar(4000),
          @leftover nvarchar(4000),
          @tmpval   nvarchar(4000)

  SET @textpos = 1
  SET @leftover = ''
  WHILE @textpos <= datalength(@list) / 2
  BEGIN
     SET @chunklen = 4000 - datalength(@leftover) / 2
     SET @tmpstr = @leftover + substring(@list, @textpos, @chunklen)
     SET @textpos = @textpos + @chunklen

     SET @startpos = 0
     SET @endpos = charindex(@delimiter COLLATE Slovenian_BIN2, @tmpstr)

     WHILE @endpos > 0
     BEGIN
        SET @tmpval = ltrim(rtrim(substring(@tmpstr, @startpos + 1,
                                            @endpos - @startpos - 1)))
        INSERT @tbl (str, nstr) VALUES(@tmpval, @tmpval)
        SET @startpos = @endpos
        SET @endpos = charindex(@delimiter COLLATE Slovenian_BIN2,
                                @tmpstr, @startpos + 1)
     END

     SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)
  END

  INSERT @tbl(str, nstr)
     VALUES (ltrim(rtrim(@leftover)), ltrim(rtrim(@leftover)))
  RETURN
END


Implementation:

CREATE PROCEDURE get_company_names_iter @customers nvarchar(2000) AS
      SELECT C.CustomerID, C.CompanyName
      FROM   Northwind..Customers C
      JOIN   iter_charlist_to_tbl(@customers, DEFAULT) s
        ON   C.CustomerID = s.nstr
   go
   EXEC get_company_names_iter 'ALFKI, BONAP, CACTU, FRANK'

strip out all non letter/number characters from a series of


I need to strip out all non letter/number characters from a series of
strings in a query. Is there a better way to do this than a bunch of
replace functions?

/*********************************
Removes any characters from
@myString that do not meet the
provided criteria.
*********************************/
CREATE FUNCTION dbo.GetCharacters(@myString varchar(500), @validChars varchar(100))
RETURNS varchar(500) AS
BEGIN

 While @myString like '%[^' + @validChars + ']%'
  Select @myString = replace(@myString,substring(@myString,patindex('%[^' + @validChars + ']%',@myString),1),'')

 Return @myString
END
Go

Declare @testStr varchar(1000),
 @i int

Set @i = 1
while @i < 255
 Select
  @TestStr = isnull(@TestStr,'') + isnull(char(@i),''),
  @i = @i + 1

Select @TestStr
Select dbo.GetCharacters(@TestStr,'a-z')
Select dbo.GetCharacters(@TestStr,'0-9')
Select dbo.GetCharacters(@TestStr,'0-9a-z')
Select dbo.GetCharacters(@TestStr,'02468bferlki')

Tuesday, April 1, 2008

1900-01-01 00:00:00.000 bug

bug: 1900-01-01 00:00:00.000 entry in SQL cause: when you enter blank string into a datetime type field the default value is 1900-01-01 00:00:00.000 fix: don't insert empty/blank string into field that is a datetime type.