Thursday, November 15        
  Home 
  Search 
  Database 
  File System 
  Components 
  Forms 
  Dates 
  E-mail 
  General 
  The Big List 
  Recent Changes 
  Downloads 
  Feedback 
  Credits 
  Privacy 

   
 Text-only version of aspfaq.com What do I need to know about the differences between Access and SQL Server?
369 requests - last updated Wednesday, November 7, 2001
 
This article will try to explain some of the differences between Access and SQL Server. It is not an exhaustive list, and in no means should be considered an ultimate authority. If you have anything to add or correct, please let us know... 
 

DATA TYPES
 
Here is a list of data types in each environment, and how they are different. Some datatypes from SQL Server were left out (e.g. SQL_VARIANT, TABLE).
    AccessSQL ServerSQL Server Definition
    Yes/NoBIT(Integer: 0 or 1)
    Number (Byte)TINYINT(Positive Integer 0 -> 255)
    Number (Integer)SMALLINT(Signed Integer -32,768 -> 32,767)
    Number (Long Integer)INT(Signed Integer -(2^31) -> (2^31)-1)
    (no equivalent)BIGINT(Signed Integer -(2^63) -> (2^63)-1)
    Number (Single)REAL(Floating precision -3.40E + 38 -> 3.40E + 38)
    Number (Double)FLOAT(Floating precision -3.40E + 38 -> 3.40E + 38)
    CurrencyMONEY(4 decimal places, -(2^63)/10000 -> ((2^63)-1)/10000)
    CurrencySMALLMONEY(4 decimal places, -(2^31)/10000 -> ((2^31)-1)/10000)
    Hyperlink(no equivalent - use VARCHAR())
    DecimalDECIMAL(Fixed precision -10^38 + 1 -> 10^38 - 1)
    NumericNUMERIC(Fixed precision -10^38 + 1 -> 10^38 - 1)
    Date/TimeDATETIME(Date+Time 1/1/1753->12/31/9999, accuracy of 3.33 ms)
    Date/TimeSMALLDATETIME(Date+Time 1/1/1900->6/6/2079, accuracy of one minute)
    AutonumberIDENTITY(INT with IDENTITY property)
    Text(n)CHAR(n)(Fixed-length non-Unicode string to 8,000 characters)
    Text(n)NCHAR(n)(Fixed-length Unicode string to 4,000 characters)
    Text(n)VARCHAR(n)(Variable-length non-Unicode string to 8,000 characters)
    Text(n)NVARCHAR(n)(Variable-length Unicode string to 4,000 characters)
    MemoTEXT(Variable-length non-Unicode string to 2,147,483,647 characters)
    OLE ObjectBINARY(Fixed-length binary data up to 8,000 characters)
    OLE ObjectVARBINARY(Variable-length binary data up to 8,000 characters)
    OLE ObjectIMAGE(Variable-length binary data up to 2,147,483,647 characters)
Some notes on usage of data types: 
 
Switching from Yes/No to BIT
    In Access, you could use integers or TRUE/FALSE keywords to determine the value of the field. In SQL Server, and especially during migration, you should use integer values only. So here are some sample queries; note that the SQL Server queries will work Access as well. 
     
    -- DETERMINING TRUE 
     
    -- Access: 
    [...] WHERE ynColumn = TRUE 
    [...] WHERE ynColumn = -1 
     
    -- SQL Server: 
    [...] WHERE ynColumn <> 0 
     
    ------------------------------ 
     
    -- DETERMINING FALSE 
     
    -- Access: 
    [...] WHERE ynColumn = FALSE 
    [...] WHERE ynColumn = 0 
     
    -- SQL Server: 
    [...] WHERE ynColumn = 0
Switching from Currency to MONEY
    You will no longer be able to use cute VBA functions like FORMAT to add dollar signs, thousand separators, and decimal places to your numbers. In fact, in Access, some of this data is actually stored along with the value. With SQL Server, this extraneous data is not stored, reducing disk space and making calculations more efficient. While you can apply this formatting in SQL Server, as explained in Article #2188, it's messy -- and better handled, IMHO, by the client application. In ASP, you can use built-in functions like FormatCurrency to apply proper formatting to your money values.
Switching from Hyperlink to VARCHAR()
    Like Currency, Access uses internal formatting to make the values stored in the application clickable. This is partly because Access is a client application, and this feature makes it easier to use. However, when you're not physically in the application, you may not want the URL to be clickable (it may just be a display value, or you may want to wrap alternate text -- or an image -- inside the <a href> tag). In SQL Server, use a VARCHAR column (likely 1024 or greater, depending on the need) and apply <a href> tags to it in the client application. Don't expect the database to maintain HTML for you... this only increases storage size, and hurts performance of searches against that column.
Switching from Date/Time to DATETIME
    When passing dates into Access from ASP or an application, you use pound signs (#) for surrounding dates. SQL Server, on the other hand, uses apostrophes ('). So the following query conversion would be required: 
     
    -- Access: 
    [...] WHERE dtColumn >= #11/05/2001# 
     
    -- SQL Server: 
    [...] WHERE dtColumn >= '11/05/2001'
     
    In addition, Access allows you to store date and time alone. SQL Server does not allow this (see Article #2206 for more info). To see if a date equals 11/05/2001 in SQL Server, you would have to convert the stored value (which includes time) to a 10-character date. Here is how a typical query would have to change: 
     
    -- Access: 
    [...] WHERE dtColumn = #11/05/2001# 
     
    -- SQL Server: 
    [...] WHERE CONVERT(CHAR(10), dtColumn, 101) = '11/05/2001'
     
    If you want to retrieve the current date and time, the syntax is slightly different: 
     
    -- Access: 
    SELECT Date() & " " & Time() 
     
    -- SQL Server: 
    SELECT GETDATE() 
    SELECT CURRENT_TIMESTAMP
     
    To get tomorrow's date, here is how your queries would look: 
     
    -- Access: 
    SELECT DateAdd("d",1,date()) 
     
    -- SQL Server: 
    SELECT CONVERT(CHAR(10), DATEADD(day, 1, GETDATE()), 101)
     
    To get the date and time 24 hours from now: 
     
    -- Access: 
    SELECT cstr(DateAdd("d",1,date())) & " " & cstr(time()) 
     
    -- SQL Server: 
    SELECT DATEADD(day, 1, GETDATE())
     
    To get the first day of the current month: 
     
    -- Access: 
    SELECT DateAdd("d",1-day(date()),date()) 
     
    -- SQL Server: 
    SELECT CONVERT(CHAR(10),GETDATE()+1-DAY(GETDATE()),101)
     
    To get the number of days in the current month: 
     
    -- Access: 
    SELECT DAY(DATEADD("m", 1, 1-DAY(date()) & date())-1) 
     
    -- SQL Server: 
    SELECT DAY(DATEADD(MONTH, 1, 1-DAY(GETDATE())+GETDATE())-1)
     
    To get the current millisecond: 
     
    -- Access: 
    SELECT "Pick a number between 1 and 1000" 
     
    -- SQL Server: 
    SELECT DATEPART(millisecond, GETDATE())
     
    To get the current weekday: 
     
    -- Access: 
    SELECT weekdayname(weekday(date())) 
     
    -- SQL Server: 
    SELECT DATENAME(WEEKDAY, GETDATE())
Switching from Autonumber to IDENTITY
    Not much difference here, except for how you define the column in DDL (CREATE TABLE) statements: 
     
    -- Access: 
    CREATE TABLE tablename (id AUTOINCREMENT) 
     
    -- SQL Server: 
    CREATE TABLE tablename (id INT IDENTITY)
Handling Strings
    There are many changes with string handling you will have to take into account when moving from Access to SQL Server. For one, you can no longer use double-quotes (") as string delimiters and ampersands (&) for string concatenation. So, a query to build a string would have to change as follows: 
     
    -- Access: 
    SELECT "Foo-" & barColumn FROM TABLE 
         
    -- SQL Server: 
    SELECT 'Foo-' + barColumn FROM TABLE
     
    (Yes, you can enable double-quote characters as string delimiters, but this requires enabling QUOTED_IDENTIFIERS at each batch, which impacts many other things and is not guaranteed to be forward compatible.) 
     
    Built-in CHR() constants in Access change slightly in SQL Server. The CHR() function is now spelled slightly differently. So, to return a carriage return + linefeed pair: 
     
    -- Access: 
    SELECT CHR(13) & CHR(10) 
         
    -- SQL Server: 
    SELECT CHAR(13) + CHAR(10)
     
    This one is confusing for many people because the CHAR keyword doubles as a function and a datatype definition.
String Functions
    There are many VBA-based functions in Access which are used to manipulate strings. Some of these functions are still supported in SQL Server, and aside from quotes and concatenation, code will port without difficulty. Others will take a bit more work. Here is a table of the functions, and they will be followed by examples. Some functions are not supported on TEXT columns; these differences are described in Article #2061
       
      AccessSQL ServerTEXT Equivalent
      CINT(), CLNG()CAST()CAST(SUBSTRING())
      INSTR()CHARINDEX()CHARINDEX()
      ISDATE()ISDATE()ISDATE(SUBSTRING())
      ISNULL()ISNULL()ISNULL()
      ISNUMERIC()ISNUMERIC()ISNUMERIC(SUBSTRING())
      LEFT()LEFT()SUBSTRING()
      LEN()LEN()DATALENGTH()
      LCASE()LOWER()LOWER(SUBSTRING())
      LTRIM()LTRIM()LTRIM(SUBSTRING())
      REPLACE()REPLACE()STUFF()
      RIGHT()RIGHT()SUBSTRING()
      RTRIM()RTRIM()RTRIM(SUBSTRING())
      CSTR()STR()STR(SUBSTRING())
      MID()SUBSTRING()SUBSTRING()
      UCASE()UPPER()UPPER(SUBSTRING())
      StrConv()n/an/a
      TRIM()n/an/a
     
    CINT(data) -> CAST(data AS INT) 
    This function converts NUMERIC data that may be stored in string format to INTEGER format for comparison and computation. Remember that SQL Server is much more strongly typed than VBA in Access, so you may find yourself using CAST a lot more than you expected. 
     
    -- Access: 
    SELECT CINT(column) 
     
    -- SQL Server: 
    SELECT CAST(column AS INT)
     
    INSTR(data, expression) -> CHARINDEX(expression, data) 
    This function returns an integer representing the character where the search expression is found within the data parameter. Note that the order of these parameters is reversed! 
     
    -- Access: 
    SELECT INSTR("franky goes to hollywood","goes") 
     
    -- SQL Server: 
    SELECT CHARINDEX('goes','franky goes to hollywood')
     
    ISDATE(data) 
    This function returns 1 if the supplied parameter is a valid date, and 0 if it is not. Aside from delimiters, the syntax is identical. 
     
    -- Access: 
    SELECT ISDATE(#12/01/2001#) 
     
    -- SQL Server: 
    SELECT ISDATE('12/01/2001')
     
    ISNULL(data) 
    This function works a bit differently in the two products. In Access, it returns 1 if the supplied parameter is NULL, and 0 if it is not. In SQL Server, there are two parameters, and the function works more like a CASE statement. The first parameter is the data you are checking; the second is what you want returned IF the first parameter is NULL (many applications outside the database haven't been designed to deal with NULL values very gracefully). The following example will return a 1 or 0 to Access, depending on whether 'column' is NULL or not; the code in SQL Server will return the column's value if it is not NULL, and will return 1 if it is NULL. The second parameter usually matches the datatype of the column you are checking. 
     
    -- Access: 
    SELECT ISNULL(column) 
     
    -- SQL Server: 
    SELECT ISNULL(column,1)
     
    ISNUMERIC(data) 
    This function returns 1 if the supplied parameter is numeric, and 0 if it is not. The syntax is identical. 
     
    SELECT ISNUMERIC(column)
     
    LEFT(data, n) 
    This function returns the leftmost n characters of data. The syntax is identical. 
     
    SELECT LEFT(column,5)
     
    LEN(data) 
    This function returns the number of characters in data. The syntax is identical. 
     
    SELECT LEN(column)
     
    LCASE(data) -> LOWER(data) 
    This function converts data to lower case. 
     
    -- Access: 
    SELECT LCASE(column) 
     
    -- SQL Server: 
    SELECT LOWER(column)
     
    LTRIM(data) 
    This function removes white space from the left of data. The syntax is identical. 
     
    SELECT LTRIM(column)
     
    REPLACE(data, expression1, expression2) 
    This function scans through data, replacing all instances of expression1 with expression2. 
     
    SELECT REPLACE(column, 'bob', 'frank')
     
    RIGHT(data, n) 
    This function returns the rightmost n characters of data. The syntax is identical. 
     
    SELECT RIGHT(column,8)
     
    RTRIM(data) 
    This function removes white space from the right of data. The syntax is identical. 
     
    SELECT RTRIM(column)
     
    CSTR(data) -> STR(data) 
    This function converts data to string format. 
     
    -- Access: 
    SELECT CSTR(column) 
     
    -- SQL Server: 
    -- if column is NUMERIC: 
    SELECT STR(column) 
    -- if column is not NUMERIC: 
    SELECT CAST(column AS VARCHAR(n))
     
    MID(data, start, length) -> SUBSTRING(data, start, length) 
    This function returns 'length' characters, starting at 'start'. 
     
    -- Access: 
    SELECT MID("franky goes to hollywood",1,6) 
     
    -- SQL Server: 
    SELECT SUBSTRING('franky goes to hollywood',1,6)
     
    UCASE(data) -> UPPER(data) 
    This function converts data to upper case. 
     
    -- Access: 
    SELECT UCASE(column) 
     
    -- SQL Server: 
    SELECT UPPER(column)
     
    StrConv 
    This function converts a string into 'proper' case (but does not deal with names like O'Hallaran or vanDerNeuts). There is no direct equivalent for StrConv in SQL Server, but you can do it per word manually: 
     
    -- Access: 
    SELECT StrConv("aaron bertrand",3) 
     
    -- SQL Server: 
    SELECT LEFT(UPPER('aaron'),1) 
    + LOWER(RIGHT('aaron',LEN('aaron')-1)) 
    + ' ' 
    + LEFT(UPPER('bertrand'),1) 
    + LOWER(RIGHT('bertrand',LEN('bertrand')-1))
     
    There is a thread stored at Google dealing with proper casing an entire block of text; you could likely implement something like that in both Access and SQL Server. 
     
    TRIM(data) 
    This function combines both LTRIM() and LTRIM(); there is no equivalent in SQL Server. To mimic the functionality, you would combine the two functions: 
     
    -- Access:  
    SELECT TRIM(column) 
    SELECT LTRIM(RTRIM(column)) 
     
    -- SQL Server: 
    SELECT LTRIM(RTRIM(column))
String Sorting
    Access and SQL Server have different priorities on string sorting. These differences revolve mostly around special characters like underscores and apostrophes. These might not change the way your application works, but you should be aware of the differences. Let's take this fictional example (SQL Server): 
     
    CREATE TABLE names 

        fname VARCHAR(10) 

    INSERT names VALUES('bob') 
    INSERT names VALUES('_bob') 
    INSERT names VALUES(' bob') 
    INSERT names VALUES('=bob') 
    INSERT names VALUES('andy') 
    INSERT names VALUES('_andy') 
    INSERT names VALUES(' andy') 
    INSERT names VALUES('=andy') 
    INSERT names VALUES('''andy') 
    INSERT names VALUES('''bob') 
    INSERT names VALUES('-andy') 
    INSERT names VALUES('-bob') 
    INSERT names VALUES('andy-bob') 
    INSERT names VALUES('bob-andy') 
     
    SELECT fname FROM names ORDER BY fname 
    DROP TABLE names
     
    Now, insert identical data into a similar table in Access 2000, and compare the SELECT results: 
     
    SQL Server  Access 2K 
    ----------  --------- 
     andy        andy 
     bob         bob 
    'andy       _andy 
    'bob        _bob 
    -andy       =andy 
    -bob        =bob 
    =andy       andy 
    =bob        'andy 
    _andy       -andy 
    _bob        andy-bob 
    andy        bob 
    andy-bob    'bob 
    bob         -bob 
    bob-andy    bob-andy
     
    Notice the inconsistencies - Access (like Windows) treats underscore (_) as the highest non-alphanumeric character. Also, it ignores apostrophe (') and hyphen (-) in sorting. You can see the other slight differences in sorting this otherwise identical list. At least they agree on which names are first and last... if only all of our queries used TOP 1! Add on top of this that both database engines' concepts of sort order are sensitive to changes in the underlying operating system's regional settings. SQL Server is also variable in its server-level (and in SQL Server 2000, table- and column-level) collation options. So, depending on all of these variables, your basic queries that sort on a text/char/varchar column will potentially start working differently upon migration.
NULL Comparisons
    SQL Server handles NULL values differently. Access assumes NULL = NULL, so two rows where a column is <NULL> would match a JOIN clause comparing the two. By default, SQL Server treats NULLs correctly as UNKNOWN, so that, depending on the settings within SQL Server, it cannot state that NULL = NULL. If you are trying to determine whether a field contains a NULL value, the following query change should be made: 
     
    -- Access: 
    [...] WHERE column = NULL 
    [...] WHERE column <> NULL 
     
    -- SQL Server: 
    [...] WHERE column IS NULL 
    [...] WHERE column IS NOT NULL
     
    If you set ANSI_NULLS OFF and are trying to compare two columns, they won't equate. A column that contains a NULL will equate with an expression that yields NULL, as will two expressions that yield NULL. But two columns that contain NULL will never be considered equal, regardless of ANSI_NULLS settings or the ANSI standards. As a workaround, use the following comparison to determine that two fields are equal AND both contain NULL (without the extra AND condition, these two would also evaluate as equal if they both contained an empty string): 
     
    [...] WHERE ISNULL(col1,'') = ISNULL(col2,'') AND col1 IS NULL
     
    Yes, it's not pretty. For more information on how SQL Server handles NULLs (and why you should avoid them), see Article #2073.

OTHER SYNTAX CHANGES
 
There are possibly dozens of other slight syntax changes that may have to be made when moving from Access to SQL Server. Here are a few of the more significant ones: 
 
IIF(expression, resultIftrue, resultIfFalse)
    IIF() is a handy inline switch comparison, which returns one result if the expression is true, and another result if the expression is false. IIF() is a VBA function, and as such, is not available in SQL Server. Thankfully, there is a more powerful function in SQL Server, called CASE. It operates much like SELECT CASE in Visual Basic. Here is an example query: 
     
    -- Access: 
    SELECT alias = IIF(Column<>0, "Yes", "No") 
        FROM table 
     
    -- SQL Server: 
    SELECT alias = CASE WHEN Column<>0 THEN 'Yes' Else 'No' END 
        FROM table
     
    SQL Server's CASE also supports multiple outcomes, for example: 
     
    SELECT alias = CASE 
        WHEN Column='a' THEN 'US' 
        WHEN Column='b' THEN 'Canada' 
        ELSE 'Foreign' 
        END 
    FROM table
DISTINCTROW
    SQL Server supports DISTINCT but does not support DISTINCTROW.

OBJECTS
 
When creating tables and other objects, keep the following limitations in mind: 
  • Access uses MAKE TABLE, while both platforms support CREATE TABLE;
  • Access object names are limited to 64 characters;
  • SQL Server 7.0+ object names are limited to 128 characters;
  • SQL Server 6.5 object names were limited to 30 characters and no spaces; and,
  • Stored queries in Access become Stored Procedures in SQL Server.

STORED QUERIES
 
Stored queries in Access are a way to store query information so that you don't have to type out ad hoc SQL all the time (and update it throughout your interface everywhere you make a similar query). Being a non-GUI guy, the easiest way I've found to create a stored query in Access is to go to Queries, open "Create query in Design View", switch to SQL View, and type in a query, such as: 
 
PARAMETERS ProductID INTEGER; 
    SELECT ProductName, Price 
        FROM Products 
        WHERE ProductID = [productID]
 
Be careful not to use any reserved words, like [name], as parameter names, or to give your parameters the SAME name as the column -- this can easily change the meaning of the query. 
 
Once you have the same schema within SQL Server, when moving to stored procedures, the basic difference you'll need to know is syntax. The above stored query becomes: 
 
CREATE PROCEDURE MyQuery 
    @ProductID INT 
AS 
BEGIN 
    SELECT ProductName, Price 
        FROM Products 
        WHERE ProductID = @productID 
END
 
You can create this stored procedure using this code through QUery Analyzer, or you can go into the Enterprise Manager GUI, open the database, open the Stored Procedures viewpane, right-click within that pane and choose New > Stored Procedure. Paste the above code (or a query that might make a bit more sense given *your* schema), click Check Syntax, and if it all works, click Apply/OK. Don't forget to set permissions! 
 
Now in both cases, you can call this code from ASP as follows: 
 
<% 
    productID = 5 
    set conn = Server.CreateObject("ADODB.Connection") 
    conn.open "<connection string>" 
    set rs = conn.execute("EXEC MyQuery " & productID) 
    do while not rs.eof 
        ' process recordset here 
        ' ... 
%>
 
See Article #2201 for a quasi-tutorial on writing stored procedures. 
 

SECURITY
 
Access is limited to security in terms of username / password on the database. It also is subject to Windows security on the file itself (as well as the folder it resides in). Typically, ASP applications must allow the anonymous Internet guest account (IUSR_<machine_Name>) to have read / write permissions on file and folder. Username / password access to the database cannot be controlled with any more granularity. 
 
SQL Server has two authentication modes, and neither are much like Access security at all. You can use Windows Authentication, which allows you direct access to domain Users and Groups from within the interface. You can also use Mixed Mode, which allows SQL Server to maintain usernames and passwords (thereby negating the need for a domain or other Windows user/group maintenance). 
 
Once you have determined an authentication mode, users have three different levels of access into the database: login (at the server level), user (at the database level), and object permissions within each database (for tables, views, stored procedures, etc). Just to add a layer of complexity, SQL Server makes it easy to "clone" users by defining server-wide roles, and adding users to that role. This is much like a Group in a Windows domain; in SQL Server, you can use the built-in definitions (and customize them), or create your own. Alterations to a role's permissions affect all users that are members of that role. 
 
Microsoft has a thorough whitepaper you should skim through before jumping into SQL Server. If you're going to deploy your own SQL Server box (as opposed to leasing a dedicated SQL Server, or a portion of one), by all means read the SQL Server Security FAQ
 

MORE INFORMATION
 
Article 2182 has a list of tools and tutorials that will aid in the migration process. Also be sure to read Microsoft's migration whitepaper for some helpful info from the vendors themselves. Finally, if you're into books, APress has a great title called From Access to SQL Server.

  

 
Powered by ORCSWeb.com