Karuta’s ASP & M$ SQLserver

Dicas, códigos e outras coisinhas de meus estudos para não esquecer…

Archive for agosto \06\UTC 2010

What are the main differences between Access and SQL Server?

Posted by karuta em agosto 6, 2010

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 (you can also seethis MSDN article for a more through treatment of the differences). If you have anything to add or correct, please let us know


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).


    Access SQL Server SQL Server Definition
    Yes/No BIT (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 -1.79E + 308 -> 1.79E + 308)
    Number (Double) FLOAT (Floating precision -3.40E + 38 -> 3.40E + 38)
    Currency MONEY (4 decimal places, -(2^63)/10000 -> ((2^63)-1)/10000)
    Currency SMALLMONEY (4 decimal places, -214,748.3648 -> 214,748.3647)
    Hyperlink (no equivalent – use VARCHAR())
    Decimal DECIMAL (Fixed precision -10^38 + 1 -> 10^38 – 1)
    Numeric NUMERIC (Fixed precision -10^38 + 1 -> 10^38 – 1)
    Date/Time DATETIME (Date+Time 1753-01-01 -> 9999-12-31, accuracy of 3.33 ms)
    Date/Time SMALLDATETIME (Date+Time 1900-01-01 -> 2079-06-06, accuracy of one minute)
    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)
    Memo TEXT (Variable-length non-Unicode string to 2,147,483,647 characters)
    Memo NTEXT (Variable-length Unicode string to 1,073,741,823 characters)
    OLE Object BINARY (Fixed-length binary data up to 8,000 characters)
    OLE Object VARBINARY (Variable-length binary data up to 8,000 characters)
    OLE Object IMAGE (Variable-length binary data up to 2,147,483,647 characters)
    IDENTITY (any numeric data type, with IDENTITY property)

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 column. 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.


    — Access:
    […] WHERE ynColumn = TRUE
    […] WHERE ynColumn = -1

    — SQL Server:
    […] WHERE ynColumn <> 0



    — 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 >= #2001-11-05#

    — SQL Server:
    […] WHERE dtColumn >= ‘20011105’

    MM/DD/YYYY format is strongly discouraged, because of the inevitable confusion (many such dates can look like DD/MM/YYYY to Canadians or Brits). The only safe format to use is YYYY-MM-DD in Access, and YYYYMMDD in SQL Server. See Article #2260 for more information. There is also further information on this later in this article.

    In addition, Access allows you to store date and time independently. SQL Server, including SQL Server 2005 (“Yukon”), does not allow this (see Article #2206 for more info). To see if a date equals 2001-11-05 in SQL Server, you would have to convert the stored value (which includes time) to a date only. Here is how a typical query would have to change:

    — Access:
    […] WHERE dtColumn = #11/05/2001#

    — SQL Server:
    […] WHERE CONVERT(CHAR(8), dtColumn, 112) = ‘20011105’

    — if dtColumn has an index, this will be more efficient:
    […] WHERE dtColumn >= ‘20011105’
    AND dtColumn < ‘20011106’

    If you want to retrieve the current date and time, the syntax is slightly different:

    — Access:
    SELECT Now()
    SELECT Date() & ” ” & Time()

    — SQL Server:

    If you want just the time:

    — Access:
    SELECT Time()

    — SQL Server:

    If you want just today’s date, there are other options:

    — Access:
    SELECT Date()

    — SQL Server:
    SELECT {fn CURDATE()} — not friendly with certain languages

    To get tomorrow’s date, here is how your queries would look:

    — Access:
    SELECT DateAdd(“d”,1,date())

    — SQL Server:

    To get the date and time 24 hours from now:

    — Access:
    SELECT cstr(DateAdd(“d”,1,date())) & ” ” & cstr(time())

    — SQL Server:

    To get the first day of the current month:

    — Access:
    SELECT DateAdd(“d”,1-day(date()),date())

    — SQL Server:

    To get the number of days in the current month:

    — Access:
    SELECT DAY(DATEADD(“m”, 1, 1-DAY(date()) & date())-1)

    — SQL Server:

    To get the current millisecond:

    — This is impossible in Access, but just for fun:
    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:

    It would be nice if you could use the same syntax against both data sources, but alas that is not the case. Try using the following in Access:

    SELECT columns FROM table WHERE dateColumn = #20030709#

    SELECT columns FROM table WHERE dateColumn = #2003-07-09#

    The first should generate an error, the second should work fine. Now check out the problems when you use the following syntax in SQL Server:

    SELECT ISDATE(‘20030713’) — 1
    SELECT ISDATE(‘2003-07-13’) — 1

    SELECT ISDATE(‘20030713’) — 1
    SELECT ISDATE(‘2003-07-13’) — 0

    Now, there is a way to make YYYY-MM-DD safe in SQL Server, and it involves using the canonical format for dates:

    SELECT ISDATE(‘{d 2003-07-13}’) — 1

    SELECT ISDATE(‘{d 2003-07-13}’) — 1

    However, I don’t believe Access will accept this format, so we’re back to square one: writing different code for each database (I guess we were there already, since Access requires # delimiters — but it would be nice if the formats were consistent).

    Like switching from Currency to Money, when you present dates in SQL Server, you lose the convenience of the FORMAT() function, which accepts multiple ways of formatting a date (e.g. ). For more information on how to overcome this change, see Article #2464 for a cheat sheet of available formatting options with CONVERT(), and Article #2460 for a roll-your-own function that mimics the FORMAT() functionality, and then some.

Switching from Autonumber to IDENTITY

    Not much difference here, except for how you define the column in DDL (CREATE TABLE) statements:

    — Access:

    — 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.)

    Another change is the ability to concatenate NULL values to a string. If you do this in Access:

    SELECT FirstName & ‘ ‘ & LastName FROM table

    If either FirstName or LastName is NULL, you will still get the portion of the string that was not NULL. In SQL Server:

    SELECT FirstName + ‘ ‘ + LastName FROM table

    If any of the values is NULL, the whole expression will yield NULL (unless you change the default setting for CONCAT_NULL_YIELDS_NULL). A common workaround is to use COALESCE around each potentially NULL value:

    SELECT COALESCE(FirstName, ”) + ‘ ‘ + COALESCE(LastName, ‘ ‘) FROM table

    (Or, avoiding NULLs in the first place… see Article #2073.)

    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.

    Another thing to note is that Access can use & or + for string concatenation. SQL Server uses & for Boolean AND, so you need to use + for all string concatenation in SQL Server. Also, keep in mind that ‘string’ + NULL = NULL, so you should always use COALESCE() on column names / values that might be NULL, in order to avoid setting the whole result to NULL.

String Functions

    • Access SQL Server TEXT Equivalent
      REPLACE() REPLACE() STUFF() (also see Article #2445)
      StrConv() n/a n/a
      TRIM() n/a n/a
  • 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.

    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’)

    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′)

    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) FROM tbl

    — SQL Server:
    SELECT ISNULL(column,1) FROM tbl

    A more intuitive function to use in SQL Server is the ANSI standard COALESCE() function. Not only does it allow you to substitute a value when a NULL is found, it will allow you to step through a series of possible values, and stop at the first non-NULL.

    SELECT COALESCE(NULL, DateUpdated, DateAdded, GETDATE()) FROM tbl

    This function returns 1 if the supplied parameter is numeric, and 0 if it is not. The syntax is identical.


    LEFT(data, n)
    This function returns the leftmost n characters of data. The syntax is identical.

    SELECT LEFT(column,5)

    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)

    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)

    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:

    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)

    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.

    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)

    — SQL Server:

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 comparisons differently. If you are trying to determine whether a column contains a NULL value, the following query change should be made:

    — Access:
    […] 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 columns 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 might want to avoid them), see Article #2073.


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:


    WITH TIES is a common usage with SELECT TOP in SQL Server. This syntax is not valid in Access (the default behavior for TOP in Access is to use WITH TIES, so in truth, there is no direct way to use “without TIES” iN Access).


    FIRST() and LAST() don’t have relevance in a relational database that is not based on physical ordering of a table – a table is, by definition, an unordered set of rows. If you want the “first” or “last” row in a dataset, you probably have some idea of which row should be first or last, so use an ORDER BY clause to force it. The order of a SELECT statement is not guaranteed, and could change from one execution to the next (it’s up to the optimizer, not the physical storage or what you’d like the order to be). The only way you can ensure a desired ordering of a result set is by using an ORDER BY clause; absolutely no exceptions. So, instead of using FIRST() or LAST(), when you move your query to SQL Server, you can use TOP 1 with an ORDER BY (or ORDER BY DESC) clause, or MIN()/MAX() (with or without a subquery).

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’
    FROM table


    Similar to IIF, Switch() can be handled in SQL Server using CASE, e.g.

    — Access:
    SELECT Switch(
    ) FROM table

    — SQL Server
    WHEN On=1 THEN ‘On’
    WHEN On=0 THEN ‘Off’
    END FROM table

    — or
    WHEN 1 THEN ‘On’
    WHEN 0 THEN ‘Off’
    END FROM table


    The Val() function in Access returns the numeric portion of a string if it appears at the beginning of the string, otherwise 0, e.g.

    Val(‘5561T5’) = 5561
    Val(‘T55615’) = 0
    Val(‘556165’) = 556165

    To mimic this functionality in SQL Server, you will need to do a little more:

    DECLARE @val VARCHAR(12)
    SET @val = ‘5561T5’
    SELECT CONVERT(INT, LEFT(@val,PATINDEX(‘%[^0-9]%’,@val+’ ‘)-1))


    SQL Server supports DISTINCT but does not support DISTINCTROW.


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.

    For information about the number and size of objects allowed in Access and SQL Server, see Article #2345.


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:

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:

@ProductID INT
SELECT ProductName, Price
FROM Products
WHERE ProductID = @productID

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 = 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.


Yes, Access has pretty little forms that you can create easily with VBA. There is no such thing in SQL Server; you will either need to develop an application (the most rapid to put together would probably be an ASP front end), or you could use Access as a front end (employing an Access Data Project, or ADP).


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.


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.


Posted in sql server | Leave a Comment »