Sss
Sss
Sss
Rows can never cross page boundaries - page size in 6.5 and earlier is 2K, in SQL
7.0 it is 8K.
Each 2048 byte page has a 32 byte header leaving 2016 bytes for data. You can
have 2 rows of 1008 bytes or 10 rows of 201 bytes. The row size also includes a
few bytes of overhead in addition to the data itself; there is more overhead if there
are variable length columns.
One row cannot be 2016 bytes - this is because when you insert/update/delete a
row, the entire row must be written to the transaction log in a log record. Log
pages also have 2016 available bytes per page, and need 50 bytes for transaction
log specific information, so this gives a maximum size for a single row of 1962
bytes.
You CAN define a table with a rowsize greater than this as long as it contains
variable/NULL columns. However, if you try at any point to insert/update a row that
has data that actually exceeds this limit then the operation will fail.
There are no workarounds for this. You will have to split the table into multiple
tables if you need more data than a row can take.
How can I output records/messages to a flat file from inside a SQL Server
TSQL script/stored-procedure/trigger?
SQL Server doesn't have a handy SPOOL command like Oracle does, but there are a
number of ways of doing what you want.
1. Use xp_cmdshell and the ECHO command. Use the > or >> redirection symbols
to either create or append to a file.
xp_cmdshell "@ECHO test message >> C:\file.fil"
2. Put the information you want into a table (note this can't be an ordinary
temporary table, but it can be a global temporary table) and then bcp it out to a file
via xp_cmdshell.
xp_cmdshell "bcp <dbname>..<tablename> out c:\file.fil -Usa -P<password> -c"
3. Write your own extended stored procedure. As this is a C program it can use
standard file access commands to achieve whatever you want.
4. Run the select through ISQL via xp_cmdshell and use the -o parameter to output
the results to a file. This example uses the -E parameter to avoild hard-coding a
userid.
With SQL 6.5 and below it is only possible to ADD a nullable column. For any other
change a new table must be created, the data copied across, and the tables
renamed around.
Certain 3rd party tools provide a GUI interface to do this, that makes it look
transparent, however they are really doing all the work described above, so if you
make the change to a large table it will take a long time to do the work.
Examples of tools are Microsoft's Visual Database Tools (part of Visual Interdev),
Sylvain Faust's SQL-Programmer, and Embarcadero's DBArtisan.
Note that there have been reports of MS VDT losing data if you amend columns on
a table and SQL does not have enough free-space to complete the task.
Where are the cascade update/delete functions in SQL Server?
There aren't any I'm afraid. These were initially thought to be going into SQL 7 but
won't be there now. They will be in a "future" SQL release.
You need to implement your own cascade functionality with triggers. See Q142480
in the MS Kb for more information on this and the ways to work with foreign keys
which cause problems due to the way that triggers work/fire.
How do I encrypt fields in SQL Server?
There is no supported, documented way of doing this, and because you can't write
user-defined functions yet then your choices are :-
2. Do it in the application, back at the VB, C etc. level. This is what most people do
and is the recommended method.
SQL 6.5 has limited row-level locking that only occurs for inserts to the end of the
last page of a table, if "sp_tableoption 'table_name', 'Insert row lock', true" is set.
See the books-online for 6.5 for more information.
SQL 6.0 and previous have no row-level locking capabilities.
You can however effectively do row level locking with version 6.5 and earlier as
long as each row takes up a whole page - thus locking 1 page is the same as 1 row.
You can do this by padding a row with CHAR NOT NULL fields until the row length is
forced to be greater than 1024 bytes. (Rows cannot span pages so this forces one
row per page).
However, you should note that although the rows on this last data page are being
row-level locked, any non-clustered index pages involved are not. These can be a
source of contention and even deadlock - when two logically distinct transactions
need to lock one or more index pages, and pessimistically in different orders.
How can I change the owner of an object?
With SQL 7.0 there is a stored-procedure to do this, however under SQL 6.5 and
earlier there is no supported method to do this.
It can be achieved by directly addressing and updating the system table concerned
though.
(The last step is necessary as portions of system tables are kept in memory by SQL
Server, and the only way to force these to update is to recycle SQL Server)
What is the limit on the number of tables in a query in SQL Server?
With SQL 6.5 and earlier the limit is 16 - regardless of which "version" of SQL you
are running - e.g. EE. With SQL 7.0 the limit is 256. These figures are hard-coded
into the SQL kernel and are arbitrarily chosen by the MS developers - but with good
reason. The more tables there are, the longer it takes to optimise a query properly.
There has to be a trade-off between the speed of running a query and the speed of
optimising it.
It *is* possible to up the limit of 16 in SQL 6.5 by setting traceflag -T105. This is
an undocumented and unsupported trace flag, so MS may not support you with any
problems on a system that is running this. However, it was allegedly put into the
product to allow some of the more complex Peoplesoft queries to run, and so it
must have had some testing/QA done on it.
Normally, if a query needs more than 16 tables then you have a very bad query
and/or database design. The best practice would be to break the query down into
smaller parts and use temporary tables to hold interim resultsets. This will also
make the query more understandable and may even speed it up as the optimiser
has more of a chance to choose correct access plans and indices.
How can I speed up SQL Server applications running over slow links?
First we need to define what a "slow" link is. Typically this is anything from
64Kbit/sec and down. On links of this speed the size of a resultset and the number
of network packets that are exchanged can make a significant difference to overall
response times.
First, either do a network trace, or use SQL Trace to see what exactly is being
transferred during a typical client session. Then try the following :-
1. If large intermediate resultsets are being returned, then see if you can write the
logic into a stored-procedure so that only the end results are returned. Try and
reduce the number of sent/received pieces of SQL by using stored-procedures as
much as possible.
2. If the connection uses ODBC and the overhead it creates running sp_serverinfo,
sp_cursor, temporary stored-procedures etc. is causing the problem then use
passthrough queries if possible and turn off the temporary stored-proc creation in
the ODBC dsn properties.
3. Configure the db-lib/ODBC connection to use the tcp-ip sockets net-lib. This
performs best over slow network connections and can make a significant difference.
5. Don't return 1000 rows to the client if all they need to see on the screen is the
first 20.
6. If there are large amounts of static data that need to be retrieved then consider
replication to a client copy of Access, SQL 6.5 Workstation or with SQL 7.0 a local
copy of SQL Server. Over slow links this should only really be used for mainly static
data.
7. Don't send any SQL across the link at all. Use Citrix or NT Terminal Edition to run
the application centrally and install ICA/RDP clients on the remote machines. The
applications then all run locally on a server next to the SQL Server (the same box
isn't recommended). The only thing that goes across the slow-link are screen-
updates, which are optimised and compressed and so will often work satisfactorily
on a 14.4Kbit/sec modem link. This also has the advantage that there is no longer
any client code to maintain at the remote sites either. There are whitepapers on
Citrix, MS and Compaq's sites about sizing the server(s) you will need to run in this
mode.
How do I store/retrieve text and image data in SQL Server?
To store/retrieve this sort of data within TSQL scripts you have to use the
WRITETEXT and READTEXT commands rather than standard INSERT/SELECT
statements. These are documented, with examples, in the books-online but are
basically a real pain to use. There are more manageable commands available from
within the relevant programming languages - e.g. RDO and ADO from VB/C can use
GetChunk and AppendChunk commands - but you still have to manage the
image/text chunks/blocks of data at a time. About the only upside of storing this
sort of data within SQL Server is that it can be kept transactionally consistent with
the other data.
If you just want to insert/retrieve an entire image/text then look at the TEXTCOPY
program (textcopy /? for parameters) in the <sql>\BINN directory. It is a
command-line program along the lines of BCP.
If the databases are on separate servers then 6.5 and below offer remote stored
procedures (look them up in the docs) but that is your only server-side choice,
there is no way to directly access the tables involved. If you need direct access
then you will need to make two separate client connections to each server and
process the data at the client end. Something like the JET engine can be used to
make this easier and make the two servers look like one.
With SQL 7.0 you can access tables across servers with a single client connection
because the fully qualified object name now allows the servername to be passed, so
you can do
=========================
delete B
from deleted, B
where deleted.pk = B.fk
delete C
from deleted, C
where deleted.pk = C.fk
=========================
The trigger is designed to delete the record in the main table and delete the related
records in the other tables. But I get the following error --
dbcc checktable(syslogs)
go
checkpoint
go
The information will then be correct until the next update/delete/insert transaction
is issued.
If your log REALLY is full - i.e. you're getting a 1105 error on syslogs, then try a
"dump transaction <dbname> with no_log". If this still doesn't fix it, then one of
the following is occurring.
1. You may have an open transaction. Check that with the following command.
use <databasename>
go
dbcc opentran(<databasename>)
2. You may have un-replicated transactions. See Q184499 for info on this and how
to clear it up.
See Q110139 and Q184499 for more information on syslogs filling up and how to
resolve them.
Why do my device sizes appear as negative values in SQL EM? It won't let
me make any changes because of this.
This is caused by a known bug in Enterprise Manager when there is greater than
2Gb of free space on a disk. It was fixed in 6.5 SP3 and above. If you are running
SQL EM from a client then you will need to apply SP3 to that as well.
Are there any "easter eggs" in SQL Server?
The only one I'm aware of is in SQL Enterprise Manager under 6.5. (It may be there
in 6.0 but I've never tried it).
Using the Enterprise Manager create a "New Server Group" called starfighter.
Register a Server called IS COOL (note there is a space there) under this new
server group. Click 'register anyway' as it won't connect.
Highlight "IS COOL" and click the "About Box " to see the development team.
Why can't I connect Enterprise Manager to my local copy of SQL Server? It
connects ok to other machines.
This is down to the way that SQL interfaces with the NT networking code. The
easiest way around this is to register the local server with a name of "." or "(local)"
- ignore the double quotes in either case. Both of these names should force SQL to
use a local-named pipe to connect which should work no matter what the default
SQL connection parameters are set to.
I'm doing a transfer using the SQL EM transfer tool, and not only is it not
transferring the objects, it is dropping them from the source. What is going
on?
This is a known bug that is caused when the server you are connecting to has a
period in the name. Typically this is because you are referring to it by tcp-ip
address.
What happens is that SQL sees the period and does a local named-pipe connect -
which it should do if the name consists of just a period, but not when it contains a
period - this means that SQL connects to the local machine as the target. As most
people have checked the "drop objects first" box it then proceeds to drop all the
objects concerned from what it thinks is the target machine - which is unfortunately
the local (source) machine.
To prevent this problem do not refer to your SQL Server's by IP address. Either :-
1. Put an entry for the name/address in your NT HOSTS file -
<NT>\SYSTEM32\DRIVERS\ETC\HOSTS.
or
2. Use SQL Client Config Manager to define a named connection for the Server in
question. In the advanced properties put the server's IP address as well as the net-
lib dll needed to connect.
Then just use the server 'name' instead of the IP address in the transfer to/from
fields.
I'm not seeing anything in the current activity screen in SQL EM. What's
gone wrong?
This is usually caused by the "select into/bulkcopy" database attribute for tempdb
being unchecked.
Set the option on again using SQL EM or sp_dboption and that should fix it.
SQL Server FAQ Backup and Restore
My SQL Server database is showing as "recovering". Why and what can I
do?
Every time SQL Server starts up it recovers all databases so that all transactions
are either committed or rolled-back. This recovery process normally only takes a
few seconds/minutes, but it the server was terminated in the middle of a long
running update, then the recovery can take at least as long as the update had
taken so far - sometimes longer due to contention on the log device.
Give it plenty of time to recover, but at the same time check the current and
previous errorlog files, and NT errorlogs, for any indications of what has happened.
If you've hit a hardware problem or SQL bug, then there WILL be errors there to
give an indication on what happened.
Check the physical disk activity lights on the server, and also check the
sysprocesses activity to see if the recovery task is using cpu and/or disk i/o. Only
on very rare occasions will SQL Server not recover the database correctly.
Additonally to check on recovery progress you could set trace flag 3412 which
writes an entry to the errorlog when each transaction is rolled forward or back.
If a database will not recover and you do NOT have a backup then you can use the
following trace flags to bypass recovery. If you use these then the database/data
may not be in a consistent state, but if you have no other choice then use them and
then immediately transfer out (using bcp or transfer tools) all the objects you
require.
If the database is still unavailable - marked as suspect - then issue the following
command to put the database into emergency mode (you'll need to allow updates
first). You can then go into the database (no need to restart SQL) and extract out
the data.
If all else fails, or you are unsure what to do, then don't hesitate to place a call with
Microsoft Product Support Services (PSS). They are there 24x7x365 to deal with
problems like this and the charge is nominal compared to the loss of your data!
Why can't I backup/restore my SQL Server database to the network?
The reason is that the MSSQLSERVER service is running under a separate set of NT
credentials. It doesn't matter who YOU are logged on as (after all SQL runs quite
happily when no-one is logged on to the console doesn't it). Therefore your logon
account and any mapped drives are irrelevant. It is SQL Server doing the backup,
not you.
The default set of NT credentials used by MSSQLSERVER is the Localsystem
account. You can check what userid that MSSQLSERVER is running under by looking
at control panel/services highlighting MSSQLSERVER and choosing the start-up
option.
So, if you want to backup to a network share you have two choices :-
1. Change the account the MSSQLSERVER service runs under to a user account with
the relevant network rights.
or
2. Amend the following registry value on the TARGET server and add the
sharename you want to dump to - the share does not then authenticate who is
coming in and so a Localsystem account will work. The server service on the target
server must be re-started before the change takes effect. Note that this effectively
removes security on that share, so you need to be careful about what is in the
share.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Param
eters\NullSessionShares
Whichever method you use, you MUST also use a UNC name to reference the file
required and not a drive letter.
You can always dump the SQL database to disk locally (or across the network with
some provisos) and then back that up to tape.
Finally, you CAN do what you want with a 3rd party backup tool that has a SQL
agent. Examples are BEI Ultrabac, Cheyenne Arcserve, Seagate BackupExec,
Legato Networker and IBM ADSM - I'm sure there are others.
These put SQL dumps (via a standard named-pipe interface) onto a standard dump
tape, potentially as part of a complete server backup and not just SQL. Obviously if
the named-pipe connection is made across the network then the dump will usually
be a lot slower than doing it locally.
Why is a SQL Server restore (LOAD DATABASE) so much slower than a
dump database?
The answer to this is that SQL initialises all pages during a load. So if you have
50Mb of data in a 5Gb database, the dump only processes the used 50Mb. But
when the load occurs it loads the 50Mb of data - which takes roughly the same time
as the dump - and then initialises the rest of the 4.95Gb of free space. This
initialisation is done page by page and goes as fast as the disk subsystem will
allow.
How can I recover a SQL Server database when all I have left is the .DAT
device?
For SQL 6.5 and below use the DISK REINIT and REFIT commands. These are
documented in the Books-Online.
Alternatively, you can download a commercial data recovery product called
MSSQLRecovery, which supports SQL Server 6.5 and 7.0 and is available at
http://www.officerecovery.com/mssql/.
How do I disable tape compression during my SQL Server backup?
Trace flag 3205 will disable tape drive compression.
mySQL = "sp_mine '" & sName & "', " & string(iNumber)
SQL Server does date-windowing for two digit dates. If you specify only the last two
digits of the year, values less than 50 are interpreted as 20yy, and values greater
than or equal to 50 are interpreted as 19yy. For example, if you specify 3, the
result is 2003. If you specify 82, the result is 1982. You must type the century
when the day is omitted or when you need a century other than the default.
However, if you mean the whole of the MS SQL Server product set including all the
gui tools, then there are a few non-showstopper problems that have been found.
These are all documented at www.microsoft.com/y2k along with MS's stance and
technical info on Y2K issues for all their products. The SQL 6.5 Y2K fix titles are also
copied at the bottom of this note.
These problems have been found, fixed and tested in SQL 6.5 and will be in Service
Pack 5 when it is released. Before that a Y2K fix (build 339) can be obtained from
MS PSS - however I would recommend waiting for SP5.
SQL 1.x, 4.x and 6.0 are NOT being tested or certified by MS. They are unlikely to
have any other problems than those found in the 6.5 product though, so if you can
live with those (and most people can), then they should be ok.
Vendor's certification should only be one part of Y2K testing anyway - the most
important part is that YOU test your clients, servers, apps, databases, networks
etc. in your production environment.
------------------
SQL 6.5 Y2K bug numbers and titles
1745
Year 2000 Problem with Expiredate
8
1793 Y2000, ExpireDate is not set correctly when year of 2000 used in DUMP
7 DATABASE
1794 RETAINDAYS: expired dump media can not be overwritten if current year is
7 >= 2000
1794
Dump db with RETAINDAYS during Y2000-9, EXPIREDATE will be set to NULL
8
1799 Y2000: dump device dumped with expiredate set to >=2000 can be override
7 with init
1766 Task Manager UI: one time task date\time spin box doesn't pick up
1 2/29/2000
1815
Web Assistant: Cannot use Year as 00 on Scheduling
3
1817
Invalid Y2K dates are accepted with no error by sp_addtask
0
1818 Invalid Y2K dates are accepted with no error by sp_purgehistory and sp_
0 updatealert
Where is the SQL Server FAQ? Or other useful SQL information.
SQL Books Online is a good source, as is Technet with 100's of techie
articles/whitepapers on SQL as well as the Knowledgebase.
Books (a few good ones, but this doesn't mean anything not listed isn't good! Many
of these go through various revisions, so check you're getting the latest and
greatest version) :-
Inside Microsoft SQL Server 6.5 : MSPress/Ron Soukup : SQL Server Internals, how
it works, why the history. Plenty of good undocumented stuff.
Microsoft SQL Server 6.5 DBA Survival Guide : SAMS/Spenik and Sledge: Short and
to the point on common DBA tasks
SQL Server 6.5 Secrets: IDG/Rensin and Fedorchek : Tons of very good scripts
Special Edition Using Microsoft SQL Server 6.5 : Que/Stephen Wynkoop : Excellent
starter book and reference work for step by step examples of performaing many
tasks.
BackOffice Resource Kit Part II : MSPress : Good stuff on SQL connectivity and
some internals, plus some nice utilities and whitepapers.
SQL Puzzles and Ansers : Morgan-K/Joe Celko : Advanced SQL programming
techniques, tricks and tips. Not SQL Server specific but highly recommended.
Significant effort and work has been put into this FAQ by Neil Pike. You can also
find some of his work on the NTFAQ
Can I compress a SQL Server .DAT device/file? Will it cause any problems?
Yes you can as long as you stop SQL first - NT needs exclusive access to a file in
order to compress it. In theory everything should be fine as SQL isn't interested in
what is happening down at the filesystem level.
In practice, this is not recommended due to the performance problems it can cause,
especially if you compress an empty database/device and then start filling it up -
there is then a lot of overhead in NTFS expanding the file as previously it had
compressed very well due to the large number of binary zeroes used to pad empty
pages.
Why does the SQL Server Database Maintenance Wizard warn about using
it on databases greater than 400MB in size?
The DMW sets up an "aggressive" set of dbcc and other healthchecks. On "large"
databases this sort of housekeeping can take a long time, so you might not want to
do everything every night. In this situation you might want to set up your own
maintenance tasks, perhaps only running checkdb once per week, and newalloc
every night, with index rebuilds once a month or so.
MS's choice of "large" is 400Mb - probably a bit low given the speed of current
cpu's/disks etc. The answer is, if you're happy with the time it takes to run the
DMW generated tasks, then stick with it, regardless of your database size.
Can I do an NT defrag on a SQL Server .DAT device/file? Will it cause any
problems or do any good?
Yes you can as long as you stop SQL first - NT needs exclusive access to a file in
order to defragment it. As long as there are no bugs in the defrag program and the
system doesn't crash in the middle of a defrag then there shouldn't be any
problems.
Will it help? Usually not much as SQL devices don't tend to change in size once they
are created, so unless a disk was badly fragmented when the device was created so
that NT could not allocate contiguous space for it all then it won't be fragmented.
If you create your SQL devices on a freshly formatted drive then you won't get any
fragmentation.
What does dbcc traceon(208) mean in SQL Server? I see it in SQL's
errorlogs, but I'm not issuing it.
This traceflag is set by some applications as they rely on SQL 6.0's quoted identifier
behaviour for object names. For differences introduced with 6.5 to this behaviour
look at the "What's New" section in the 6.5 books-online.
Where can I get the ANSI92 SQL information from?
This is information is only available from ANSI themselves and as far as I know is
only available on paper (to discourage piracy). They charge for the information -
they have to have some form of income stream after all.
Therefore with large bcp's/select into's - when a lot of extents need allocating - the
log can still fill. In which case it needs to be made larger.
How can I view the SQL Server log?
Most of the information in the SQL log (syslogs) is not accessible via standard SQL
commands. The ways of accessing this information are :-
1. You can get transaction id and operation type only (no data) through a select *
from syslogs. Or use the following code (courtesy of Tibor Karaszi) to make it a bit
more readable.
SELECT
xactid AS TRAN_ID,
CASE op
WHEN 0 THEN 'BEGINXACT Start Transaction'
WHEN 1 THEN 'Not Used'
WHEN 2 THEN 'Not Used'
WHEN 3 THEN 'Not Used'
WHEN 4 THEN 'INSERT Insert Row'
WHEN 5 THEN 'DELETE Delete Row'
WHEN 6 THEN 'INSIND Deferred Update step 2 insert record'
WHEN 7 THEN 'IINSERT NC Index Insert'
WHEN 8 THEN 'IDELETE NC Index Delete'
WHEN 9 THEN 'MODIFY Modify Row'
WHEN 10 THEN 'NOOP'
WHEN 11 THEN 'INOOP Deferred Update step 1 insert record'
WHEN 12 THEN 'DNOOP Deferred Update step 1 delete record'
WHEN 13 THEN 'ALLOC Allocation'
WHEN 14 THEN 'DBNEXTID Extent allocation'
WHEN 15 THEN 'EXTENT Extent allocation'
WHEN 16 THEN 'SPLIT Page split'
WHEN 17 THEN 'CHECKPOINT'
WHEN 18 THEN 'SAVEXACT Savepoint'
WHEN 19 THEN 'CMD'
WHEN 20 THEN 'DEXTENT Deallocate extent'
WHEN 21 THEN 'DEALLOC Deallocate page'
WHEN 22 THEN 'DROPEXTS Delete all extents on alloc pg'
WHEN 23 THEN 'AEXTENT Alloc extent - mark all pgs used'
WHEN 24 THEN 'SALLOC Alloc new page for split'
WHEN 25 THEN 'Not Used'
WHEN 26 THEN 'Not Used'
WHEN 27 THEN 'SORT Sort allocations'
WHEN 28 THEN 'SODEALLOC Related to sort allocations'
WHEN 29 THEN 'ALTDB Alter database record'
WHEN 30 THEN 'ENDXACT End Transaction'
WHEN 31 THEN 'SORTTS Related to sort allocations'
WHEN 32 THEN 'TEXT Log record of direct TEXT insert'
WHEN 33 THEN 'INOOPTEXT Log record for deferred TEXT insert'
WHEN 34 THEN 'DNOOPTEXT Log record for deferred TEXT delete'
WHEN 35 THEN 'INSINDTEXT Indirrect insert log record'
WHEN 36 THEN 'TEXTDELETE Delete text log record'
WHEN 37 THEN 'SORTEDSPLIT Used for sorted splits'
WHEN 38 THEN 'CHGINDSTAT Incremental sysindexes stat changes'
WHEN 39 THEN 'CHGINDPG Direct change to sysindexes'
WHEN 40 THEN 'TXTPTR Info log row WHEN retrieving TEXTPTR'
WHEN 41 THEN 'TEXTINFO Info log for WRITETEXT/UPDATETEXT'
WHEN 42 THEN 'RESETIDENT Used WHEN a truncate table resets an identity value'
WHEN 43 THEN 'UNDO Compensating log record for Insert Only Row Locking
(IORL)'
WHEN 44 THEN 'INSERT_IORL Insert with Row Locking record'
WHEN 45 THEN 'INSIND_IORL INSIND with IORL'
WHEN 46 THEN 'IINSERT_IORL IINDEX with IORL'
WHEN 47 THEN 'SPLIT_IORL Page split with IORL'
WHEN 48 THEN 'SALLOC_IORL Alloc new page for split with IORL'
WHEN 49 THEN 'ALLOC_IORL Allocation with IORL'
WHEN 50 THEN 'PREALLOCLOG Pre-allocate log space for CLRs'
ELSE 'Unknown Type' END AS LOG_RECORD
FROM syslogs
2. dbcc log command. Not well documented, but some details below. Note that as
with most undocumented dbcc commands you need to do a dbcc traceon(3604)
first to see the output.
3. Logview from www.dbsg.com.
4. Log Analyzer from www.platinum.com
(All these are currently for 6.5 or earlier)
---------------------------------------
dbcc log [ (@dbid, @objid, @pagenum, @rownum, @records, @type [, @printopt])
]
dbcc log (5, 0, 0, 0, -1, 0, 1) // Show the last begin transaction record in the log
Parameters:
@dbid Database ID
@objid Object ID
A negative value indicates that @pagenum & @rownum represent a row in the log
to use as a starting point in the scan of the log.
A value of zero indicates that log records for changes to @pagenum will be included
in the commands output.
A positive value followed by a non-zero value for @pagenum indicates that
@pagenum and @rownum represent a transaction ID. Log records for that
transaction will be included in the output.
A positive value followed by zero values for @pagenum and @rownum indicates an
object ID. Log records for changes to that object will be included in the output.
@pagenum page number
@rownum row number in the log
Together with @pagenum, this is either a starting point in a scan of the log or a
transaction id.
@records number of records to examine. If positive, the first
@type
@printopt
I have tried Admin, and admin user (tony) SQL login as sa. I am stumped, I would
like to know how to subscribe/publish, but I urgently need my original problem
solved.
To solve this problem, follow these steps:
1) Open "Services" -window from Control Panel.
2) Find the "SQLExecutive" service from the list and select it.
3) Push the "Startup" -button and check the "Log On As" selection. Value "This
Account:" (and account name) should be selected.
#2: No tables showing up for replication
One other area to consider if you're having troubles with replication is that of
unique keys on the tables you're attempting to publish. If you don't have unique
keys defined, the table will not be listed as available for publishing. You *must*
have a key defined for all tables you plan to publish.
Set up Microsoft SQL Server service. · Note: Microsoft SQL Server must start up
using a user account that has been given administrator privileges. The account
must also allow the user to logon as a service. This allows Microsoft SQL Server to
interact with email. · Note: By default, SQL Server 6.5 creates an account named
" SQLExecutiveCmdExec". Verify that this account exists and is set up properly:
After that go to www.microsoft.com/support and check out the following SQL Mail
knowledgebase articles :-
Any other problems then do a search for "SQLMAIL" and you'll find other more
specific articles.
Unable to Get Mail to Work Properly
I cannot get Sql Server 6.0 mail to start under Windows NT 4.0, I setup a valid
profile for the built in NT mail service but sql mail will never start.
One way you can enable this option is to install MS Exchange Server/Client and
create a profile (private information store, if I'm right) that would represent an
account that recieves mail from SQLServer 6.5. The SQL Mail option in SQLServer
can then be configured to point to this profile... This scenario works quite well for
me. I can have mail sent by SQLServer, directly into my Exchange/Outlook Inbox.
I'm not sure of SQLServer 6.0 version's support for this scenario. Also, I'm not sure
if a similar option exists for users of MS Mail.
Can I send mail from a stored procedure or trigger?
Use the xp_sendmail procedure.
SQLServer versions after 4.2x can be setup to start an msmail session
automatically without a user being logged in. For example, in 6.0 you setup mail
parameters in the SQLSetup program. Be sure to tell it to start the mail session
automatically. (Otherwise you manually start the mail session with the xp_startmail
procedure -- specify the user name and password as parameters to the call.)
If you are running SQLServer service under the system account, you must create a
share for your mail postoffice and the share must be marked in the registry to allow
services to access it. The registry key is
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parame
ters\NullSession Shares...
This information is found in the Microsoft Knowledgebase, article Q118501.
This url seems to work:
http://198.105.232.6:80/KB/bussys/sql_odbc/Q118501.htm
With the exception of "materialised" tables like syslocks and sysprocesses you can
pretty much use standard SQL commands to update the system tables.
Some system tables SQL Server updates internally via it's own api's and some it
does via standard TSQL. Any updates it does via standard TSQL would result in a
trigger firing, however there is no list of what tables this would work with, and it
certainly wouldn't be supported if you did use it.
To update system tables first you have to set the "allow updates" flag as follows :-
Then go can make updates - make sure you always do this within a transaction so
that if you affect more rows than you meant to then it can be rolled back.
Afterwards reset the 'allow updates' flag.
There are also a few occasions where MS have put in "extra" protection to stop
users mucking about. One example is sysindexes where you must specify the
name, id and indid in the where clause otherwise the update will fail.
SQL Server FAQ - Transfer/move objects/data
How do I transfer data from another DBMS/format to SQL Server? (e.g.
from FoxPro, Access, AS/400, DB/2, Oracle....)
There are a variety of methods :-
1. For MS-Access you can try the free Access upsizing wizards available from MS's
website - check out the softlib area under www.microsoft.com/support. These will
convert from versions of Access to SQL 4.x and 6.x. No conversion to 7.x is
currently available, so convert to 6.5 and then upgrade that copy of SQL Server to
7.0.
2. If you can unload the data from the foreign dbms into flat-file format - e.g. tab
separated, comma-separated, fixed-format etc. then you can use the SQL BCP.EXE
tool. This is a command-line program and is fully doc'd in the books-online. It is the
fastest way of getting data into/out of SQL Server, but it only works via flat-files.
3. If you have an ODBC driver for the other format then there are several 3rd party
tools you can use that offer transfer/migration functionality and are GUI-based, but
can also be automated and run from the command-line. These tools can be used to
copy to/from ANY ODBC data sources - they don't have to be SQL Server at one
end. Examples of these sorts of tools are :-
Data Junction
SQL Mover
InfoPump
DBArtisan
4. If you have SQL 7.0 then this comes with a tool called DTS that works in a
similar manner to the above. It works with any ODBC or OLE-DB accessible data
source. Again it doesn't have to be SQL 7.0 at one end. However if you weren't
using it to migrate to/from SQL 7.0 you would have to check whether there were
any licensing implications.
5. Specifically for the AS/400 there are a couple of tools that have been around for
some time - offering real-time replication as well as transfer.
Data Mirror
Symbiator
How do I remove the tempdb database from master?
Do the following.
1. Configure tempdb to be in RAM for 2 MB. Use SQL EM or sp_configure.
2. Execute a reconfigure with override.
3. Stop and restart SQL Server.
4. Add a new device for tempdb. Do not call it temp_db - any other name should be
ok
5. Make that new device a 'default' device; make sure no other device is marked as
default, especially master. You can check/change default status either using SQL
EM, or the sp_diskdefault stored-procedure. Both are fully described in the books-
online.
6. Configure tempdb to NOT be in RAM (set value to 0)
7. Execute a reconfigure with override.
8. Stop and restart SQL Server
9. Re-mark whichever device(s) you want to be default.
I am having problems with SQL Server running bcp from xp_cmdshell -
why does it not run or see the files I want it to?
First make sure that you have the rights to run xp_cmdshell - do an xp_cmdshell
'dir' and check you get a resultset of filenames back.
Then be aware that the MSSQLSERVER service is running under a separate set of
NT credentials. It doesn't matter who YOU are logged on as (after all SQL runs
quite happily when no-one is logged on to the console doesn't it). Therefore your
logon account and any mapped drives are irrelevant. It is SQL Server running the
bcp, not you, so as far as drive letters go it can only see the local ones - local
meaning on the server, do not be confused into thinking that if you are issuing the
query from a workstation that the query is referencing your workstation's local
drives.
So, if you want bcp running under xp_cmdshell to access a network resource you
have two choices :-
1. Change the account the MSSQLSERVER service runs under to a user account with
the relevant network rights.
or
2. Amend the following registry value on the TARGET server and add the
sharename you want to access - the share does not then authenticate who is
coming in and so a Localsystem account will work. The server service on the target
server must be re-started before the change takes effect. Note that this effectively
removes security on that share, so you need to be careful about what is in the
share.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Param
eters\NullSessionShares
Whichever method you use, you MUST use a UNC name to reference the resources
required and not a drive letter.
i.e. xp_cmdshell 'bcp servername..tablename out \\server01\share\bcp.fil
.............'
How can I move a SQL Server device from one disk to another, or rename
it?
There are two ways :-
1. Use device mirroring. Mirror the device to the "new" location and then break the
mirror and delete the old device. This method does not need SQL downtime and can
be done via the gui or via TSQL.
2. Use the sp_movedevice sp that is documented in the Books-Online. After making
the change stop SQL Server, physically move the device, then restart it. Therefore
this method requires downtime, but it is faster as using OS level commands is
faster than SQL mirroring.
All that sp_movedevice does is update the phyname in the sysdevices table.
Note that the above method works for all USER databases. If you want to move
master this way, then note that the phyname parameter in sysdevices is only for
documentation - you might as well change it anyway to keep things in line. The
actual method SQL uses for locating the master device is by looking in the registry
:-
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\Paramet
ers\SQLArg0
With SQL 7.0 the byte re-ordering is done for you and so dumps and loads across
architectures are supported.
How do I transfer data between SQL Server databases / across servers?
1. The fastest method for whole databases is to use the DUMP DATABASE and
LOAD DATABASE commands. You need to make sure that the databases are the
same size and made up of the same segment fragments in the same order. If you
do an sp_help_revdatabase on both this will allow you to check the required DDL
for this. You can DUMP and LOAD from a local tape device and transport the tape if
you do not have a network connection.
2. If you only want tables/data you can use the SQL BCP.EXE tool. This is a
command-line program and is fully doc'd in the books-online. It works on one table
at a time and allows you to create a flat file on disk.
4. SQL Enterprise Manager comes with a built-in gui transfer function, and SQL 7
comes with a separate, equivalent tool. This allows transfer of all objects between
two databases/servers but requires a network connection between the two.
How long the operating system takes to kill a network connection, or whether it is
done at all, depends on the net-lib and network protocol used. For parameters on
keep-alive frames and session time-outs for the relevant network protocol the best
guide is the NT Server resource kit, which describes how NT's various networ layers
work.
Typically, named-pipe connections over netbeui will be timed out quite quickly,
followed by named-pipes over IP. If you're using tcp-ip sockets then these sessions
aren't timed-out at all by default.
How do I get the printdmp.exe program in SQL Server to work?
Basically you don't. The output it produces from AV dump files that it analyses is
still useless to anyone without the SQL Server source code. (If you have SQL
Server source code, then please send me a copy!)
If you are getting AV dumps and you're already on the latest service pack then your
only option is to make a paid support call to MS PSS for them to resolve the issue.
If they want you to run printdmp then they'll give you the info on how to run it.
However, I've never known them want anyone to do this - they usually want the
whole dump file, along with SQL errorlog(s), sp_configure output etc.
I am getting a blue screen / completely hung machine / server restart on
my SQL Server/client.
All the above can ONLY be caused by a problem with something in NT running in
Kernel Mode. e.g. bits of NT, scsi drivers, network drivers, video drivers etc.
All SQL Server code runs in user mode, just like any normal program. Therefore it
is no more capable of causing a blue-screen than Word is. It can only "cause" the
problem in as much as it might hit the disk subsystem hard and expose a bug in a
scsi driver.
If you are getting one of these problems then it needs to be investigated like any
other NT blue-screen problem. i.e. check the driver/program in control at the time,
use dumpexam, apply a newer servicepack, contact MS.
I have a query that seems to lock other users out of the system. Especially
with tempdb. What is going on?
In situations like this the usual problem is with locks. Check with sp_lock or
sp_lock2 what the offending query is doing.
One common occurrence that people fell foul of was introduced in SQL 6.5 when MS
decided to let table creation be allowed in transactions by making it an ATOMIC
transaction. A by product of this is that when a SELECT INTO is done it locks out
system tables in the database concerned and prevents other users from accessing
them. With a long-running select into this can cause real problems.
MS recognised this and as long as you have service pack 1 applied you can set
traceflag -T5302 to remove this behaviour. Check out Q153441 for more info.
My SQL Server database has been marked "suspect" - what can I do?
In addition to these ideas, also check out www.microsoft.com/support for the MS
Knowledgebase. Specifically Q165918.
Firstly look in <sql>\LOG and look at all recent errorlog(s). There WILL be an
indication here as to why the database has been marked suspect. You need to fix
whatever the problem is first (i.e. missing file, permissions problem, hardware error
etc.)
Then, when the problem has been fixed and you're either sure that the data is
going to be ok, or you have no backup anyway, so you've nothing to lose, then
change the database status to normal and restart SQL Server. To change the
database status, and to get more information on recovery, look up the
sp_resetstatus sp in the Books Online.
If you don't have access to sp_resetstatus information, then the short version of
this is :-
If the database still goes back into suspect mode, and you can't fix the original
problem, and you have no recent backup, then you can get information out of the
database by putting it into emergency mode. If you do this, extract the
data/objects out with bcp/transfer manager and then rebuild the database. Note
that the data may be corrupt or transactionally inconsistent.
Issue the following command to put the database into emergency mode (you'll
need to allow updates first)
UPDATE master..sysdatabases SET status=-32768 WHERE name='<dbname>'
Why can't I get at a network file when I run a program with xp_cmdshell
from SQL Server?
The reason is that the MSSQLSERVER service is running under a separate set of NT
credentials. It doesn't matter who YOU are logged on as (after all SQL runs quite
happily when no-one is logged on to the console doesn't it). Therefore your logon
account and any mapped drives are irrelevant. It is SQL Server running the
program (e.g. bcp) not you.
So, if you want a program running under xp_cmdshell to access a network resource
you have two choices :-
1. Change the account the MSSQLSERVER service runs under to a user account with
the relevant network rights.
or
2. Amend the following registry value on the TARGET server and add the
sharename you want to access - the share does not then authenticate who is
coming in and so a Localsystem account will work. The server service on the target
server must be re-started before the change takes effect. Note that this effectively
removes security on that share, so you need to be careful about what is in the
share.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Param
eters\NullSessionShares
Whichever method you use, you MUST use a UNC name to reference the resources
required and not a drive letter.
Assuming it's not a database corruption, then follow the following diagnostic
process :-
1. Check the Microsoft Kb on Technet (if you don't have Technet then order it
now!). Also check the on-line website at www.microsoft.com/support which is more
up to date than Technet. Search on kbbug AND AV AND SQL to find all documented
AV bugs. Many contain workarounds.
2. Are you on the latest version of SQL Server and the latest service pack? MS fix a
lot of AV errors in every service pack, so it is definitely worth getting current. If
you're not on the latest service pack then that is the first thing MS are going to ask
you to do if you contact them anyway.
3. Check the SQL errorlog and save away all the messages - especially anything
telling you what SQL was being executed at the time.
4. Check the \<sql>\LOG directory for SQLxxxx.DMP files that may have been
created. These contain information on what SQL Server was doing at the time,
module stack traces etc. Save these away for MS support as necessary. (Though
there is a PRINTDMP.EXE utility supplied the output of this is still of no use to
anyone unless they have the SQLServer C source code)
5. Can you re-create the problem at will? If the SQL being run is not shown in the
errorlog, then find out what the user/developer was doing at the time. Use SQL
Trace to capture the actual SQL code being run if you can. If you can't recreate it,
it's still worth reporting as long as you have the errorlog(s) and dump file(s).
6. If you can re-create the problem, then see if you can create a reproduction script
to show the problem. This needs to be capable of running on a brand-new install of
SQL Server on a new database. Therefore it needs to contain all tables, user
defined data types, triggers, views etc. needed to show the problem. If it needs
data then try and keep this to a minimum. (If the script/data is reasonably short
then post to one of the
newsgroups and one of MVP's can report it to MS for you).
7. Can you work around the problem by re-writing the SQL? Even with a
reproduction script MS are unlikely to turn a fix around quickly - unless you are a
multi-million dollar customer. And even then you wouldn't just be applying one
small fix, it would be a latest build with lots of other fixes too - it won't have been
regression tested, so it could cause more damage than it fixed anyway.
8. Report the problem to MS PSS. PLEASE do this even if you can workaround it.
Unless MS get these bug reports then they can't fix them. (With a repro script an
MVP will do it for you). Your call fee WILL be re-imbursed as all calls about bugs are
free. (However, on the "normal" support-line the person answering the phone can't
know it's a bug, so they'll need your credit card details anyway).
With SQL 7 there is a new utility that will garner most of this information for you
automatically. It is called sqldiag -
sqldiag -U<login> -P<password> -O<output filename>
I am missing the whole of MSDB, or just some tables - how do I create
them?
In the <sql>\INSTALL directory are the scripts that SQL runs itself to create the
MSDB database and it's tables. If you need to re-create it, then make sure the
devices are already there and then run :-
instmsdb.sql
servrmsgs.sql
web.sql
via ISQL/W or ISQL.
How can I fix a corruption in a system table?
If the problem can be fixed with an index re-create, then there is a system stored-
procedure to do this.
sp_fixindex <db_name>,<system_table_name>,<index-id>
e.g. sp_fixindex pubs,sysindexes,2
You can also issue the relevant dbcc command directly if sp_fixindex refuses to
attempt the fix - e.g. for a non-clustered index on sysobjects
If the above do not work, then the only choice is to create a new database and then
use the transfer tools in SQL EM to copy the good data and objects across.
Why do my SQL Server identity values get out of synch causing
gaps/duplicates etc.? Is there anything I can do about it?
Why? Because of inherent problems with the way they were implemented. For
performance reasons the current identity value isn't updated and committed in the
system tables every time a row is inserted. This would lead to unacceptably bad
performance, especially with SQL 6.x's page-level locking architecture - it could
even lead to deadlocks. Therefore the value is stored in memory and only
committed to disk when a clean shutdown of SQL occurs.
So, if SQL doesn't shut down cleanly, or there is some memory problem caused by
an exception violation then the value will not be correct next time SQL starts. There
are also some other bugs that would cause the value not to be updated, but MS
fixed most of these with 6.5 SP3.
The only thing you can do about it is to put dbcc checkident(<tablename>)
statements in a startup stored-procedure (details of this in the BOL) so that the
values get fixed every time SQL starts - obviously for very large tables this may
take a few minutes.
MS's own code/stored-procedures are not immune to this. One very common case
is where you get duplicate key messages on sysbackuphistory (in MSDB) when you
do a database dump. This is because the table uses an identity column.
(MS promise this situation will not occur with SQL 7.x as they have re-worked how
the identity columns function internally)
What are the *.DMP files that appear in the SQL Server log directory. I've
tried printing them with PRINTDMP.EXE but it doesn't work.
These are a sign that SQL Server has had a "handled access violation" - a gpf.
The dump files contain information on what SQL Server was doing at the time,
module stack traces etc. Though there is a PRINTDMP.EXE utility supplied the
output of this is still of no use to anyone unless they have the SQLServer C source
code.
Save the dumps away, together with errorlog info, what SQL was running at the
time etc. and contact MS PSS for support in resolving the problem. (Assuming
you've already applied the latest service pack and dbcc'd your databases to make
sure there are no problems there)
I'm getting an error 1117 in SQL Server. Can I rebuild the extents
somehow?
It is recommended that you select/bcp out all the relevant data and then recreate
the objects concerned. However, if you want to attempt a rebuild of the extents
then make a backup first, and then try the following after putting the database into
single-user mode first :-
Parameters:
@db_id Id of the database
@object_id Id of the object to be rebuild
@index_id Id of the index to be rebuild
Why do I have problems revoking permissions on some tables with SQL
Server? The command works ok, but the users still have permissions (as
shown by sp_helprotect)
This is a known bug in SQL Server with tables that have 8n-1 columns. I.e. 7, 15,
22 etc.
To workaround it remove all entries from sysprotects and then re-grant permissions
as necessary.
use <dbname>
go
exec sp_configure 'allow updates',1
go
reconfigure with override
go
delete sysprotects where id = object_id('<tblname>')
go
exec sp_configure 'allow updates',0
go
reconfigure with override
go
Why do I get the message "WARNING: Process being freed while holding
Dataserver semaphore" in SQL Server.
This is a fairly common error.
1. Check for previous errors - this is often not the actual error that occurred but is a
symptom of a previous error that has caused SQL Server to get confused. It then
ends up trying to exit a routine without having cleared up all the resources that it
owns. It is the previous error that you should look up in Technet/MS
Knowledgebase.
3. Apply the latest servicepack - this or the underlying error may well have been
fixed already.
4. If none of the above apply, and your problem does not match any known,
documented issue then you will have to call MS PSS and open a paid fault call. If
you can reproduce the problem with a script run against a new, clean database
then it should be fairly easy for a fix to be written.
I'm getting a 1112 error on SQL Server - what's going on?
This message will only occur with SQL 4.x and is fixed in all subsequent versions.
The ONLY permanent fix is to upgrade to SQL 6.0 or above.
The error occurs if SQL has crashed during the allocation of an extent - this
sometimes leaves a "being allocated" bit set in the extent. When SQL comes to
need that extent to expand a table then you get the error because SQL thinks the
bit should never me set and some form of corruption has occurred.
Because SQL always allocates extents in the same order, once you get the error
you will carry on getting it unless you drop some objects and free up extents nearer
the start of the database that it can allocate ok. This only puts off the time till the
next 1112.
To "fix" the error you can get and run a file called 1112.EXE from MS PSS or
ftp.microsoft.com/bussys/sql/transfer. This contains details of what to do to run it -
note the database needs to be in single-user mode at the time. All it does is whiz
through the extent map and reset any bits that show as "being allocated".
Note this "fix" only fixes that particular occurence of the problem. The problem will
come back, so move to a supported version of SQL that has a permanent fix for this
problem.
I'm getting a "sort failed 1501" message on SQL Server - what's going on?
This is usually caused by a time-out when creating an index - if you see "state 12"
after the 1501 then it definitely is. This hard-coded timeout was upped with SQL
6.5 SP3 and is rarely seen now (though it does still sometimes occur). It is normally
caused by a slow or congested disk subsystem - either get some faster
disks/controllers or make sure that no other processes are contending on the same
disks at the time of the query that causes the error.
If the above doesn't fit, then you can try upping the "sort pages" parameter in
sp_configure. This may keep more of the sort in memory and reduce the iterations
it goes through and thus prevent the error.
Other than that all you can do is contact MS PSS with the error message, including
state number, and let them delve through the code to see what piece of code the
state message you're getting is in. (The state codes are unique)
I've just changed NT domain for my SQL Server/clients - why can't I
connect to the server any more?
This isn't a SQL issue, it's an NT one. If you are using a net-lib that requires NT
authentication - e.g. named-pipes or multiprotocol - then you MUST be able to
authenticate to the copy of NT running SQL Server.
You can test whether you can do this by doing a "NET VIEW \\servername" from a
command prompt on the client. If you get an access denied message, or get
prompted for a password, then you aren't being authenticated.
If this happens then you need to setup a trust between the domains. Or, you could
use a net-lib that does not need authentication - e.g. tcp-ip sockets.
If you can't have a trust (and really this IS the best method) then you can override
the NT details by doing a "net use \\<server>\ipc$
/user:<serverdomain>\<userid> <password>" with an account that is in the
domain. But this is a manual process and prone to fail when the password changes.
I've put tempdb in ram and now I can't restart my SQL Server.
This is because the memory allocated by SQL Server does NOT include tempdb in
ram. There must be enough memory for SQL, tempdb AND NT otherwise SQL will
fail to start. To recover from this.
1. Stop SQL Server and SQL Executive. Also make sure that SQL Enterprise
Manager isn't running.
2. Go to the <sql>\binn directory and type "sqlservr -c -f" - this will start SQL in
single-user mode with a minimum config.
3. Ignore the text messages in this window - but wait for them to finish appearing
(shouldn't take more than 10-20 seconds)
4. SQL Server is now started.
5. Go to another window and start ISQL/W and connect locally with the sa userid.
6. In ISQL/W issue the following commands :-
sp_configure tempdb, 0
go
reconfigure
go
7. Now go back to the window SQL is running in and type "shutdown" and enter
8. SQL Server should shut down. If it doesn't then hit <ctrl-c> to shut it down.
9. Now you should be able to start SQL normally and connect. You will need to re-
size tempdb as it will have gone back to the original 2Mb in master.
I can't run SQL Server Enterprise Manager. I'm getting an error SQLOLE
OLE object could not be registered. Class not registered (80040154).
This is a problem with the class not being resgistered in the registry properly. Use
the regsvr32 utility to re-register it :-
regsvr32 <sql>\binn\sqlole65.dll
Replacing <sql> with the full drive/dir that SQL is installed into.
I am having problems with SQL Server running bcp from xp_cmdshell -
why does it not run or see the files I want it to?
First make sure that you have the rights to run xp_cmdshell - do an xp_cmdshell
'dir' and check you get a resultset of filenames back.
Then be aware that the MSSQLSERVER service is running under a separate set of
NT credentials. It doesn't matter who YOU are logged on as (after all SQL runs
quite happily when no-one is logged on to the console doesn't it). Therefore your
logon account and any mapped drives are irrelevant. It is SQL Server running the
bcp, not you, so as far as drive letters go it can only see the local ones - local
meaning on the server, do not be confused into thinking that if you are issuing the
query from a workstation that the query is referencing your workstation's local
drives.
So, if you want bcp running under xp_cmdshell to access a network resource you
have two choices :-
1. Change the account the MSSQLSERVER service runs under to a user account with
the relevant network rights.
or
2. Amend the following registry value on the TARGET server and add the
sharename you want to access - the share does not then authenticate who is
coming in and so a Localsystem account will work. The server service on the target
server must be re-started before the change takes effect. Note that this effectively
removes security on that share, so you need to be careful about what is in the
share.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Param
eters\NullSessionShares
Whichever method you use, you MUST use a UNC name to reference the resources
required and not a drive letter.
Go
You can raise this message from your code like this :-
INSERT Customers (CustomerName)
VALUES ('Rick Nelson')
IF @@Error <> 0
RAISERROR
(50001,16,1, 'Customers')
5) How to get the Rowcount as well as Error at the same time
Normally when we run a Query, we check if the query was executed successfully or
not before commiting it.
DECLARE @CustomerId Int
SET @CustomerId = 1
Begin Transaction
Update Orders
Set OrderDate = GetDate()
Where CustomerId = @CustomerId
IF @@Error <> 0
Begin
Raiserror('Failed
to update Orders',16,1)
Rollback
Transaction
End
Commit Transaction
But what if you also want to get the number of records which were effected by this
query? If you do a @@Rowcount after your Error checking statement then you are
going to get 0 as the value of @@Recordcount would have been reset. And if you
place @@Recordcount before the error-checking statement then your @@Error
would get reset. So what's the solution to get both of them at the same time ? Save
both the values in a local variable and then check that local variable. Here's how it
can be done.
DECLARE @Rcount Int
DECLARE @ErrNum Int
SET @Rcount = 0
SET @ErrNum = 0
SET @CustomerId = 1
Begin Transaction
Update Orders
Set OrderDate = GetDate()
Where CustomerId = @CustomerId
Commit Transaction
c) From Registry :-
· Go to
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServer\MSSQLServer\Parameter
s. · Add new string value. · Specify the 'Name' as SQLArg( n) & 'Data' as -m. Where
n is t he argum ent num ber in t he list of argum ent s.
Caut ion: Be careful while editing the Registry. Incorrectly setting up Registry values
can cause unpredictable behavior.
c) From Registry :-
· Go to
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServer\MSSQLServer\Parameter
s. · Add new string value. · Specify the 'Name' as SQLArg( n) & 'Data' as -f. Where n
is t he argum ent num ber in t he list of argum ent s.
Caut ion: Be careful while editing the Registry. Incorrectly setting up Registry values
can cause unpredictable behavior.
3) How to get Output parameter value from Dynamic execution of a Query
Sometimes you have to execute a Query dynamically using Exec(@Sql). This
method works fine as long as you don't want any output values from the @Sql
query. But there's another method (sp_Executesql) that allows you to execute
queries dynamically as well as get their output values.
The syntax :-
EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@parm=@parmIN,
@parm1OUT=@parmRET1 OUTPUT,@parm2OUT=@parmRET2 OUTPUT
Example :-
DECLARE @IntVariable INT
DECLARE @SQLString nVARCHAR(500)
DECLARE @ParmDefinition nVARCHAR(500)
DECLARE @Lastlname nVARCHAR(30)
a) Using sp_rename
· Make sure that no user is using the database. · Make the database in the single
user mode. You can do this by using sp_dboption.
Note : For renaming the database, you can also use sp_renamedb.
-dD:\MSSQL7\data\master.mdf
-eD:\MSSQL7\log\ErrorLog
-lD:\MSSQL7\data\mastlog.ldf
-d is the fully qualified path for the master database data file.
- e is the fully qualified path for the error log file.
- l is the fully qualified path for the master database log file.
· Remove these values and specify the new values. For example :
- dE:\SQLDATA\master.mdf
- lE:\SQLDATA\mastlog.ldf
Note : You can specify a new path for the error log file as well.
· Stop SQL Server. · Copy the Master.mdf and Mastlog.ldf files to the new location
(E:\Sqldata). · Restart SQL Server.
2) How to Rename a Server
· Rename the physical server. · Reboot the server. · Run the SQL Server setup
program. This will change the Registry entries. The setup will prompt you to
"Upgrade" SQL Server. Choose "yes". · Reboot the server. · Connect to the new
server name in Query analyzer. · Run this code: sp_dropserver <old server name>
· Run this code: sp_addserver <new server name>, local · Add the entry for the
new Server name in Enterprise manager and delete the entry for the Old server
name.
3) How to detect & rectify Orphaned Users in a Database
Logins are associated to users by the security identifiers (SIDs), which are stored in
the Master database. When you restore a database to a different server, the SID
may be different resulting in a mismatch between the Login-User association. These
users, without a valid login association, are called 'Orphaned Users'.
Use Northwind
Go
sp_change_users_login 'Report'
http://www.swynk.com/faq/sql/sqlfaq_general.asp
This document was created with Win2PDF available at http://www.daneprairie.com.
The unregistered version of Win2PDF is for evaluation or non-commercial use only.