Mssql error code

Useful links, scripts, tools and best practice for Microsoft SQL Server Database

Microsoft SQL Server Ошибки

Useful links

  • System Error Messages
  • Database Engine Error Severities
  • Integration Services Error and Message Reference
  • View and Read SQL Server Setup Log Files
  • Troubleshoot the SQL Server Utility
  • Common Issues: Licensing Errors
  • SQL Server 2016 Distributed Replay Errors
  • The Instance ID MSSQLSERVER Is Already In Use
  • SQL Server: Detach/Attach Gotchas!

SQL Server All Errors List

SELECT message_id, severity, text
  FROM sys.messages
 WHERE language_id = 1033; /* assuming US English */

Your language_id you can find in
sys.syslanguages
system view, column msglangid:

langid dateformat datefirst upgrade name alias months shortmonths days lcid msglangid
0 mdy 7 0 us_english English January,February,March,April,May,June,July,August,September,October,November,December Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday 1033 1033
1 dmy 1 0 Deutsch German Januar,Februar,März,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember Jan,Feb,Mär,Apr,Mai,Jun,Jul,Aug,Sep,Okt,Nov,Dez Montag,Dienstag,Mittwoch,Donnerstag,Freitag,Samstag,Sonntag 1031 1031
2 dmy 1 0 Français French janvier,février,mars,avril,mai,juin,juillet,août,septembre,octobre,novembre,décembre janv,févr,mars,avr,mai,juin,juil,août,sept,oct,nov,déc lundi,mardi,mercredi,jeudi,vendredi,samedi,dimanche 1036 1036
3 ymd 7 0 日本語 Japanese 01,02,03,04,05,06,07,08,09,10,11,12 01,02,03,04,05,06,07,08,09,10,11,12 月曜日,火曜日,水曜日,木曜日,金曜日,土曜日,日曜日 1041 1041
4 dmy 1 0 Dansk Danish januar,februar,marts,april,maj,juni,juli,august,september,oktober,november,december jan,feb,mar,apr,maj,jun,jul,aug,sep,okt,nov,dec mandag,tirsdag,onsdag,torsdag,fredag,lørdag,søndag 1030 1030
5 dmy 1 0 Español Spanish Enero,Febrero,Marzo,Abril,Mayo,Junio,Julio,Agosto,Septiembre,Octubre,Noviembre,Diciembre Ene,Feb,Mar,Abr,May,Jun,Jul,Ago,Sep,Oct,Nov,Dic Lunes,Martes,Miércoles,Jueves,Viernes,Sábado,Domingo 3082 3082
6 dmy 1 0 Italiano Italian gennaio,febbraio,marzo,aprile,maggio,giugno,luglio,agosto,settembre,ottobre,novembre,dicembre gen,feb,mar,apr,mag,giu,lug,ago,set,ott,nov,dic lunedì,martedì,mercoledì,giovedì,venerdì,sabato,domenica 1040 1040
7 dmy 1 0 Nederlands Dutch januari,februari,maart,april,mei,juni,juli,augustus,september,oktober,november,december jan,feb,mrt,apr,mei,jun,jul,aug,sep,okt,nov,dec maandag,dinsdag,woensdag,donderdag,vrijdag,zaterdag,zondag 1043 1043
8 dmy 1 0 Norsk Norwegian januar,februar,mars,april,mai,juni,juli,august,september,oktober,november,desember jan,feb,mar,apr,mai,jun,jul,aug,sep,okt,nov,des mandag,tirsdag,onsdag,torsdag,fredag,lørdag,søndag 2068 2068
9 dmy 7 0 Português Portuguese janeiro,fevereiro,março,abril,maio,junho,julho,agosto,setembro,outubro,novembro,dezembro jan,fev,mar,abr,mai,jun,jul,ago,set,out,nov,dez segunda-feira,terça-feira,quarta-feira,quinta-feira,sexta-feira,sábado,domingo 2070 2070
10 dmy 1 0 Suomi Finnish tammikuuta,helmikuuta,maaliskuuta,huhtikuuta,toukokuuta,kesäkuuta,heinäkuuta,elokuuta,syyskuuta,lokakuuta,marraskuuta,joulukuuta tammi,helmi,maalis,huhti,touko,kesä,heinä,elo,syys,loka,marras,joulu maanantai,tiistai,keskiviikko,torstai,perjantai,lauantai,sunnuntai 1035 1035
11 ymd 1 0 Svenska Swedish januari,februari,mars,april,maj,juni,juli,augusti,september,oktober,november,december jan,feb,mar,apr,maj,jun,jul,aug,sep,okt,nov,dec måndag,tisdag,onsdag,torsdag,fredag,lördag,söndag 1053 1053
12 dmy 1 0 čeština Czech leden,únor,březen,duben,květen,červen,červenec,srpen,září,říjen,listopad,prosinec I,II,III,IV,V,VI,VII,VIII,IX,X,XI,XII pondělí,úterý,středa,čtvrtek,pátek,sobota,neděle 1029 1029
13 ymd 1 0 magyar Hungarian január,február,március,április,május,június,július,augusztus,szeptember,október,november,december jan,febr,márc,ápr,máj,jún,júl,aug,szept,okt,nov,dec hétfő,kedd,szerda,csütörtök,péntek,szombat,vasárnap 1038 1038
14 dmy 1 0 polski Polish styczeń,luty,marzec,kwiecień,maj,czerwiec,lipiec,sierpień,wrzesień,październik,listopad,grudzień I,II,III,IV,V,VI,VII,VIII,IX,X,XI,XII poniedziałek,wtorek,środa,czwartek,piątek,sobota,niedziela 1045 1045
15 dmy 1 0 română Romanian ianuarie,februarie,martie,aprilie,mai,iunie,iulie,august,septembrie,octombrie,noiembrie,decembrie Ian,Feb,Mar,Apr,Mai,Iun,Iul,Aug,Sep,Oct,Nov,Dec luni,marţi,miercuri,joi,vineri,sîmbătă,duminică 1048 1048
16 ymd 1 0 hrvatski Croatian siječanj,veljača,ožujak,travanj,svibanj,lipanj,srpanj,kolovoz,rujan,listopad,studeni,prosinac sij,vel,ožu,tra,svi,lip,srp,kol,ruj,lis,stu,pro ponedjeljak,utorak,srijeda,četvrtak,petak,subota,nedjelja 1050 1050
17 dmy 1 0 slovenčina Slovak január,február,marec,apríl,máj,jún,júl,august,september,október,november,december I,II,III,IV,V,VI,VII,VIII,IX,X,XI,XII pondelok,utorok,streda,štvrtok,piatok,sobota,nedeľa 1051 1051
18 dmy 1 0 slovenski Slovenian januar,februar,marec,april,maj,junij,julij,avgust,september,oktober,november,december jan,feb,mar,apr,maj,jun,jul,avg,sept,okt,nov,dec ponedeljek,torek,sreda,četrtek,petek,sobota,nedelja 1060 1060
19 dmy 1 0 ελληνικά Greek Ιανουαρίου,Φεβρουαρίου,Μαρτίου,Απριλίου,Μα_ου,Ιουνίου,Ιουλίου,Αυγούστου,Σεπτεμβρίου,Οκτωβρίου,Νοεμβρίου,Δεκεμβρίου Ιαν,Φεβ,Μαρ,Απρ,Μαϊ,Ιουν,Ιουλ,Αυγ,Σεπ,Οκτ,Νοε,Δεκ Δευτέρα,Τρίτη,Τετάρτη,Πέμπτη,Παρασκευή,Σάββατο,Κυριακή 1032 1032
20 dmy 1 0 български Bulgarian януари,февруари,март,април,май,юни,юли,август,септември,октомври,ноември,декември януари,февруари,март,април,май,юни,юли,август,септември,октомври,ноември,декември понеделник,вторник,сряда,четвъртък,петък,събота,неделя 1026 1026
21 dmy 1 0 русский Russian Январь,Февраль,Март,Апрель,Май,Июнь,Июль,Август,Сентябрь,Октябрь,Ноябрь,Декабрь янв,фев,мар,апр,май,июн,июл,авг,сен,окт,ноя,дек понедельник,вторник,среда,четверг,пятница,суббота,воскресенье 1049 1049
22 dmy 1 0 Türkçe Turkish Ocak,Şubat,Mart,Nisan,Mayıs,Haziran,Temmuz,Ağustos,Eylül,Ekim,Kasım,Aralık Oca,Şub,Mar,Nis,May,Haz,Tem,Ağu,Eyl,Eki,Kas,Ara Pazartesi,Salı,Çarşamba,Perşembe,Cuma,Cumartesi,Pazar 1055 1055
23 dmy 1 0 British British English January,February,March,April,May,June,July,August,September,October,November,December Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday 2057 1033
24 dmy 1 0 eesti Estonian jaanuar,veebruar,märts,aprill,mai,juuni,juuli,august,september,oktoober,november,detsember jaan,veebr,märts,apr,mai,juuni,juuli,aug,sept,okt,nov,dets esmaspäev,teisipäev,kolmapäev,neljapäev,reede,laupäev,pühapäev 1061 1061
25 ymd 1 0 latviešu Latvian janvāris,februāris,marts,aprīlis,maijs,jūnijs,jūlijs,augusts,septembris,oktobris,novembris,decembris jan,feb,mar,apr,mai,jūn,jūl,aug,sep,okt,nov,dec pirmdiena,otrdiena,trešdiena,ceturtdiena,piektdiena,sestdiena,svētdiena 1062 1062
26 ymd 1 0 lietuvių Lithuanian sausis,vasaris,kovas,balandis,gegužė,birželis,liepa,rugpjūtis,rugsėjis,spalis,lapkritis,gruodis sau,vas,kov,bal,geg,bir,lie,rgp,rgs,spl,lap,grd pirmadienis,antradienis,trečiadienis,ketvirtadienis,penktadienis,šeštadienis,sekmadienis 1063 1063
27 dmy 7 0 Português (Brasil) Brazilian Janeiro,Fevereiro,Março,Abril,Maio,Junho,Julho,Agosto,Setembro,Outubro,Novembro,Dezembro Jan,Fev,Mar,Abr,Mai,Jun,Jul,Ago,Set,Out,Nov,Dez Segunda-Feira,Terça-Feira,Quarta-Feira,Quinta-Feira,Sexta-Feira,Sábado,Domingo 1046 1046
28 ymd 7 0 繁體中文 Traditional Chinese 一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月 01,02,03,04,05,06,07,08,09,10,11,12 星期一,星期二,星期三,星期四,星期五,星期六,星期日 1028 1028
29 ymd 7 0 한국어 Korean 01,02,03,04,05,06,07,08,09,10,11,12 01,02,03,04,05,06,07,08,09,10,11,12 월요일,화요일,수요일,목요일,금요일,토요일,일요일 1042 1042
30 ymd 7 0 简体中文 Simplified Chinese 01,02,03,04,05,06,07,08,09,10,11,12 01,02,03,04,05,06,07,08,09,10,11,12 星期一,星期二,星期三,星期四,星期五,星期六,星期日 2052 2052
31 dmy 1 0 Arabic Arabic Muharram,Safar,Rabie I,Rabie II,Jumada I,Jumada II,Rajab,Shaaban,Ramadan,Shawwal,Thou Alqadah,Thou Alhajja Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday 1025 1025
32 dmy 7 0 ไทย Thai มกราคม,กุมภาพันธ์,มีนาคม,เมษายน,พฤษภาคม,มิถุนายน,กรกฎาคม,สิงหาคม,กันยายน,ตุลาคม,พฤศจิกายน,ธันวาคม ม.ค.,ก.พ.,มี.ค.,เม.ย.,พ.ค.,มิ.ย.,ก.ค.,ส.ค.,ก.ย.,ต.ค.,พ.ย.,ธ.ค. จันทร์,อังคาร,พุธ,พฤหัสบดี,ศุกร์,เสาร์,อาทิตย์ 1054 1054
33 dmy 1 0 norsk (bokmål) Bokmål januar,februar,mars,april,mai,juni,juli,august,september,oktober,november,desember jan,feb,mar,apr,mai,jun,jul,aug,sep,okt,nov,des mandag,tirsdag,onsdag,torsdag,fredag,lørdag,søndag 1044 1044

Levels of Severity

Severity level Description
0-9 Informational messages that return status information or report errors that are not severe. The Database Engine does not raise system errors with severities of 0 through 9.
10 Informational messages that return status information or report errors that are not severe. For compatibility reasons, the Database Engine converts severity 10 to severity 0 before returning the error information to the calling application.
11-16 Indicate errors that can be corrected by the user.
11 Indicates that the given object or entity does not exist.
12 A special severity for queries that do not use locking because of special query hints. In some cases, read operations performed by these statements could result in inconsistent data, since locks are not taken to guarantee consistency.
13 Indicates transaction deadlock errors.
14 Indicates security-related errors, such as permission denied.
15 Indicates syntax errors in the Transact-SQL command.
16 Indicates general errors that can be corrected by the user.
17-19 Indicate software errors that cannot be corrected by the user. Inform your system administrator of the problem.
17 Indicates that the statement caused SQL Server to run out of resources (such as memory, locks, or disk space for the database) or to exceed some limit set by the system administrator.
18 Indicates a problem in the Database Engine software, but the statement completes execution, and the connection to the instance of the Database Engine is maintained. The system administrator should be informed every time a message with a severity level of 18 occurs.
19 Indicates that a nonconfigurable Database Engine limit has been exceeded and the current batch process has been terminated. Error messages with a severity level of 19 or higher stop the execution of the current batch. Severity level 19 errors are rare and must be corrected by the system administrator or your primary support provider. Contact your system administrator when a message with a severity level 19 is raised. Error messages with a severity level from 19 through 25 are written to the error log.
20-24 Indicate system problems and are fatal errors, which means that the Database Engine task that is executing a statement or batch is no longer running. The task records information about what occurred and then terminates. In most cases, the application connection to the instance of the Database Engine may also terminate. If this happens, depending on the problem, the application might not be able to reconnect.
Error messages in this range can affect all of the processes accessing data in the same database and may indicate that a database or object is damaged. Error messages with a severity level from 19 through 24 are written to the error log.
20 Indicates that a statement has encountered a problem. Because the problem has affected only the current task, it is unlikely that the database itself has been damaged.
21 Indicates that a problem has been encountered that affects all tasks in the current database, but it is unlikely that the database itself has been damaged.
22 Indicates that the table or index specified in the message has been damaged by a software or hardware problem.
Severity level 22 errors occur rarely. If one occurs, run DBCC CHECKDB to determine whether other objects in the database are also damaged. The problem might be in the buffer cache only and not on the disk itself. If so, restarting the instance of the Database Engine corrects the problem. To continue working, you must reconnect to the instance of the Database Engine; otherwise, use DBCC to repair the problem. In some cases, you may have to restore the database.
If restarting the instance of the Database Engine does not correct the problem, then the problem is on the disk. Sometimes destroying the object specified in the error message can solve the problem. For example, if the message reports that the instance of the Database Engine has found a row with a length of 0 in a nonclustered index, delete the index and rebuild it.
23 Indicates that the integrity of the entire database is in question because of a hardware or software problem.
Severity level 23 errors occur rarely. If one occurs, run DBCC CHECKDB to determine the extent of the damage. The problem might be in the cache only and not on the disk itself. If so, restarting the instance of the Database Engine corrects the problem. To continue working, you must reconnect to the instance of the Database Engine; otherwise, use DBCC to repair the problem. In some cases, you may have to restore the database.
24 Indicates a media failure. The system administrator may have to restore the database. You may also have to call your hardware vendor.

SQL Server Errors

message_id Description Article
0 You may see “out of user memory quota” message in errorlog when you use In-Memory OLTP feature … Out of user memory quota
0 Logon Failure: The User has not Been Granted. The operating system returned the error ????? while … Compressed backup errors
0 A transport-level error has occurred when receiving results from the server. link1
0 The MSSQLSERVER service was unable to log on as SQLAuthoritySQLFarmService with the currently c … The User has not Been Granted
0 A server error occurred on current command. The results, if any, should be discarded. Who owns your availability groups?
0 A network-related issue or instance-specific error occured while establishing a connection to SQL Server Cannot Connect to SQL Server
0 Connecting to Azure SQL Database: Requested tenant identifier ‘00000000-0000-0000-0000-000000000000’ is… Requested tenant identifier
102 Incorrect syntax near ‘%.*ls’. 102_link1,102_link2
120 The select list for the INSERT statement contains fewer items than the insert list. The number of … 120_link1
121 The select list for the INSERT statement contains more items than the insert list. The number of … 121_link1
131 The size (%d) given to the %S_MSG ‘%.*ls’ exceeds the maximum allowed for any data type (%d). 131_link1
145 ORDER BY items must appear in the select list if SELECT DISTINCT is specified. 145_link1
156 Incorrect syntax near the keyword ‘ORDER’. 156_link1
207 Invalid column name ‘%.*ls’. 207_link1
213 Column name or number of supplied values does not match table definition. 213_link1,213_link2
229 The %ls permission was denied on the object ‘%.ls’, database ‘%.ls’, schema ‘%.*ls’. 229_link1
241 Conversion failed when converting date and/or time from character string. 241_link1
257 Implicit conversion from data type %ls to %ls is not allowed. Use the CONVERT function to run this query 257_link1
264 The column name ‘%.*ls’ is specified more than once in the SET clause or column list of an INSERT … 264_link1
297 The user does not have permission to perform this action. 297_link1
352 The table-valued parameter «%.*ls» must be declared with the READONLY option. 352_link1
459 Collation ‘%.*ls’ is supported on Unicode data types only and cannot be applied to char, varchar or … 459_link1
535 The datediff function resulted in an overflow. The number of dateparts separating two date/time 535_link1
596 Cannot continue execution because the session is in the kill state. 596_link1,596_link2,596_link3
650 You can only specify the READPAST lock in the READ COMMITTED or REPEATABLE READ isolation levels. 650_link1
657 Could not disable support for increased partitions in database … 657_link1
666 The maximum system-generated unique value for a duplicate group was exceeded for index with … 666_link1
701 There is insufficient system memory in resource pool ‘%ls’ to run this query. … 701_link1,701_link2
824 SQL Server detected a logical consistency-based I/O error … 824_link1,824_link2,KB2152734,824_link3
825 The operating system returned error %ls to SQL Server. It failed creating event for a %S_MSG at … 825_link1
913 Could Not Find Database %d. Database May Not be Activated Yet or May be in Transition … 913_link1
922 Database ‘%.*ls’ is being recovered. Waiting until recovery is finished. 922_link1
926 Database ‘%.*ls’ cannot be opened. It has been marked SUSPECT by recovery. See the SQL Server errorlog … 926_link1
1052 Conflicting %ls options «%ls» and «%ls». 1052_link1
1065 The NOLOCK and READUNCOMMITTED lock hints are not allowed for target tables of INSERT, UPDATE, DELETE … 1065_link1
1105 Could not allocate space for object ‘%.ls’%.ls in database ‘%.ls’ because the ‘%.ls’ filegroup is … 1105_link1
1204 The instance of the SQL Server Database Engine cannot obtain a LOCK resource at this time. Rerun your … 1204_link1
1205 Transaction (Process ID %d) was deadlocked on %.*ls resources with another process and has been chosen … 1205_link1
1222 Lock request time out period exceeded. 1222_link1
1219 Your session has been disconnected because of a high priority DDL operation. 1219_link1
1480 The %S_MSG database «%.*ls» is changing roles from «%ls» to «%ls» because the mirroring session or … 1480_link1
1701 Creating or altering table %ls failed because the minimum row size would be 8061, including 10 b … 1701_link1
1807 Could not obtain exclusive lock on database ‘model’. Retry the operation later. … 1807_link1
1904 The statistics on table has 65 columns in the key list … 1904_link1
1908 Column ‘%.ls’ is partitioning column of the index ‘%.ls’. Partition columns for a unique index … 1908_link1
2533 Table error: page %S_PGID allocated to object ID %d, index ID %d, partition ID %I64d, alloc unit ID … 2533_link1
2534 Table error: page %S_PGID, whose header indicates that it is allocated to object ID %d, index ID %d, … 2534_link1
2812 Could not find stored procedure ‘%.*ls’. 2812_link1
3101 Exclusive access could not be obtained because the database is in use. … 3101_link1
3154 The backup set holds a backup of a database other than the existing … 3154_link1
3241 The media family on device ‘%ls’ is incorrectly formed. SQL Server cannot process this media fam … 3241_link1
3314 During undoing of a logged operation in database ‘%.*ls’, an error occurred at log record ID %S … 3314_link1
3634 The operating system returned the error ‘%ls’ while attempting ‘%ls’ on ‘%ls’. … 3634_link1
3637 A parallel operation cannot be started from a DAC connection. 3637_link1
3743 The database ‘%.*ls’ is enabled for database mirroring. Database mirroring must be removed befor … 3743_link1
3906 Failed to update database «%.*ls» because the database is read-only. 3906_link1
3930 The current transaction cannot be committed and cannot support operations that write to the log … 3930_link1
3956 Snapshot isolation transaction failed to start in database ‘%.*ls’ because the ALTER DATABASE command … 3956_link1
3960 Snapshot isolation transaction aborted due to update conflict. You cannot use snapshot isolation to … 3960_link1
4064 Cannot open user default database. Login failed.Login failed. … 4064_link1
4189 Cannot convert to text/ntext or collate to ‘%.*ls’ because these legacy LOB types do not support UTF-8 … 4189_link1
4353 Conflicting file relocations have been specified for file ‘%.*ls’. Only a single WITH MOVE clause … 4353_link1
4629 Permissions on server scoped catalog views or system stored procedures or extended stored … 4629_link1
4901 ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition … 4901_link1
4922 ALTER TABLE ALTER COLUMN Address failed because one or more objects access this column. … 4922_link1
4934 Computed column ‘%.ls’ in table ‘%.ls’ cannot be persisted because the column does user or … 4934_link1
4947 ALTER TABLE SWITCH statement failed. There is no identical index in source table ‘%.*ls’ for the … 4947_link1
5004 To use ALTER DATABASE, the database must be in a writable state in which a checkpoint can be executed. 5004_link1
5011 User does not have permission to alter database ‘%.*ls’, the database does not exist, or the database … 5011_link1
5061 ALTER DATABASE failed because a lock could not be placed on database ‘%.*ls’. Try again later. 5061_link1
5084 Setting database option %ls to %ls for database ‘%.*ls’. 5084_link1
5120 Unable to open the physical file … Operating system error 5: «5(Access is denied.)» … SQL SERVER — FIX Error 5120
5123 CREATE FILE encountered operating system error «%ls»(The system cannot find the path specified.) … 5123_link1, 5123_link2
5171 %.*ls is not a primary database file. 5171_link1
5172 The header for file ‘%ls’ is not a valid database file header. The %ls property is incorrect. 5172_link1
5235 %lsDBCC %ls (%ls%ls%ls)%ls executed by %ls terminated abnormally due to error state %d. Elapsed time: … 5235_link1
5846 Common language runtime (CLR) execution is not supported under lightweight pooling. Disable one of two … 5846_link1
6335 XML datatype instance has too many levels of nested nodes. Maximum allowed depth is 128 levels. 6335_link1
6348 Specified collection ‘%.*ls’ cannot be created because it already exists or you do not have permission. 6348_link1
6401 Cannot roll back %.*ls. No transaction or savepoint of that name was found. 6401_link1
7341 Cannot get the current row value of column «%ls.%ls» from OLE DB provider «%ls» for linked server «%ls … 7341_link1
7344 The OLE DB provider «%ls» for linked server «%ls» could not %ls table «%ls» because of column … 7344_link1
7356 The OLE DB provider «%ls» for linked server «%ls» supplied inconsistent metadata for a column. … 7356_link1
7357 Cannot process the object «%ls». The OLE DB provider «%ls» for linked server «%ls» indicates that … 7357_link1, 7357_link2
7391 The operation could not be performed because OLE DB provider «%ls» for linked server «%ls» … … 7391_link2
7719 CREATE/ALTER partition function failed as only maximum of 1000 partitions can be created. … 657_link1
7926 Check statement aborted. The database could not be checked as a database snapshot could not be created … 7926_link1
8101 An explicit value for the identity column in table ‘%.*ls’ can only be specified when a column list is … 8101_link1
8107 IDENTITY_INSERT is already ON for table ‘%.ls.%.ls.%.*ls’. Cannot perform SET operation for table ‘% … 8107_link1
8115 Arithmetic overflow error converting %ls to data type %ls. 8115_link1
8116 Argument data type %ls is invalid for argument %d of %ls function. 8116_link1
8117 Operand data type %ls is invalid for %ls operator. 8117_link1
8180 Statement(s) could not be prepared. 8180_link1
8127 Column «%.ls.%.ls» is invalid in the ORDER BY clause because it is not contained in either an … 8127_link1
8152 String or binary data would be truncated. 8152_link1
8624 Internal Query Processor Error: The query processor could not produce a query plan. 8624_link1
8645 A timeout occurred while waiting for memory resources to execute the query in resource pool ‘%ls’ (%ld … 8645_link1
8651 Could not perform the operation because the requested memory grant was not available in resource … 8651_link1
8672 The MERGE statement attempted to UPDATE or DELETE the same row more than once… … 8672_link1
8909 Table error: Object ID %d, index ID %d, partition ID %I64d, alloc unit ID %I64d (type %.*ls), pa … 8909_link1
8921 Check terminated. A failure was detected while collecting facts. Possibly tempdb out of space or … 8921_link1
8928 Object ID %d, index ID %d, partition ID %I64d, alloc unit ID %I64d (type %.*ls): Page %S_PGID could not… 8928_link1
8939 Table error: Object ID %d, index ID %d, partition ID %I64d, alloc unit ID %I64d (type %.*ls), page … 8939_link1
8948 Database error: Page %S_PGID is marked with the wrong type in PFS page %S_PGID. PFS status 0x%x … 8948_link1
9001 The log for database ‘%.*ls’ is not available. Check the operating system error log for related … 9001_link1
9002 The transaction log for database ‘%ls’ is full due to ‘%ls’. … 9002_link1,9002_link2,9002_link3
9105 The provided statistics stream is corrupt. 9105_link1
9642 An error occurred in a Service Broker/Database Mirroring transport connection endpoint, Error: %i, … 9105_link1
10314 An error occurred in the Microsoft .NET Framework while trying to load assembly id %d. The server may … 10314_link1,10314_link2
10637 Cannot perform this operation on ‘%.*ls’ with ID %I64d as one or more indexes are currently in … 10637_link1
10794 The %S_MSG ‘%ls’ is not supported with %S_MSG. 10794_link1,10794_link2
11442 Columnstore index creation is not supported in tempdb when memory-optimized metadata mode is enabled. … [11442_link1][51]
11535 EXECUTE statement failed because its WITH RESULT SETS clause specified %d result set(s), and the … 11535_link1
12349 Operation not supported for memory optimized tables having columnstore index. 12349_link1
13609 JSON text is not properly formatted. Unexpected character ‘%lc’ is found at position %d. 13609_link1
13515 Setting SYSTEM_VERSIONING to ON failed because history table ‘%.*ls’ has custom unique keys defined. … 13515_link1
13518 Setting SYSTEM_VERSIONING to ON failed because history table ‘%.*ls’ has IDENTITY column specification … 13518_link1
13523 Setting SYSTEM_VERSIONING to ON failed because table ‘%.ls’ has %d columns and table ‘%.ls’ has %d … 13523_link1
13543 Setting SYSTEM_VERSIONING to ON failed because history table ‘%.*ls’ contains invalid records with end … 13543_link1
13570 The use of replication is not supported with system-versioned temporal table ‘%s’ 13570_link1
13573 Setting SYSTEM_VERSIONING to ON failed because history table ‘%.*ls’ contains overlapping records. 13573_link1
13575 ADD PERIOD FOR SYSTEM_TIME failed because table ‘%.*ls’ contains records where end of period is not … 13575_link1
13901 Identifier ‘%.*ls’ in a MATCH clause is not a node table or an alias for a node table. 13901_link1
13902 Identifier ‘%.*ls’ in a MATCH clause is not an edge table or an alias for an edge table. 13902_link1
15002 The procedure ‘sys.sp_dbcmptlevel’ cannot be executed within a transaction. … 15002_link1
15021 Invalid value given for parameter %s. Specify a valid parameter value. 15021_link1
15136 The database principal is set as the execution context of one or more procedures, functions, … 15136_link1
15190 There are still remote logins or linked logins for the server ‘%s’. 15190_link1
15199 The current security context cannot be reverted. Please switch to the original database where … 15199_link1
15274 Access to the remote server is denied because the current security context is not trusted. 15274_link1
15404 Could not obtain information about Windows NT group/user ‘%ls’, error code %#lx. 15404_link1
15406 Cannot execute as the server principal because the principal «%.*ls» does not exist, this type of … 15406_link1
15457 Configuration option ‘%ls’ changed from %ld to %ld. Run the RECONFIGURE statement to install. 5457_link1
17051 SQL Server evaluation edition has expired. 17051_link1
17182 TDSSNIClient initialization failed with error 0x%lx, status code 0x%lx. Reason: %S_MSG %.*ls 17182_link1
17190 Initializing the FallBack certificate failed with error code: %d, state: %d, error number: %d. … 17190_link1
17300 SQL Server was unable to run a new system task, either because there is insufficient memory or the … 17300_link1
17836 Length specified in network packet payload did not match number of bytes read; the connection has been … 17836_link1
18054 Error %d, severity %d, state %d was raised, but no message with that error number was found in … 18054_link1
18272 During restore restart, an I/O error occurred on checkpoint file ‘%s’ (operating system error %s … 18272_link1
18357 Reason: An attempt to login using SQL authentication failed. Server is configured for Integrated … 18357_link1
18401 Login failed for user ‘%.*ls’. Reason: Server is in script upgrade mode. Only administrator can connect… 18401_link1
18452 Login failed. The login is from an untrusted domain and cannot be used with Windows authenticati … 18452_link1
18456 Login failed for user ‘%.ls’.%.ls%.*ls 18456_link1
20598 The row was not found at the Subscriber when applying the replicated %S_MSG command for Table ‘%s’ with… 20598_link1
22911 The capture job cannot be used by Change Data Capture to extract changes from the log when … 22911_link1
25713 The value specified for %S_MSG, «%.ls», %S_MSG, «%.ls», is invalid. 25713_link1,25713_link2
26023 Server TCP provider failed to listen on [ %s <%s> %d]. Tcp port is already in use. 26023_link1
33111 Cannot find server %S_MSG with thumbprint ‘%.*ls’. 33111_link1
33206 SQL Server Audit failed to create the audit file ‘%s’. Make sure that the disk is not full and … 33206_link1
35217 The thread pool for Always On Availability Groups was unable to start a new worker thread because … [35217_link1]
35250 The connection to the primary replica is not active. The command cannot be processed. 35250_link1
35264 Always On Availability Groups data movement for database ‘%.*ls’ has been suspended for the following … 35264_link1
35320 Column store indexes are not allowed on tables for which the durability option SCHEMA_ONLY is specified. 35320_link1
35337 UPDATE STATISTICS failed because statistics cannot be updated on a columnstore index. … 35337_link1
35343 The statement failed. Column ‘%.*ls’ has a data type that cannot participate in a columnstore index. 35343_link1
39004 A ‘%s’ script error occurred during execution of ‘sp_execute_external_script’ with HRESULT 0x%x. 39004_link1
41121 The local availability replica of availability group ‘%.*ls’ cannot accept signal ‘%s’ in its current … 41121_link1
41317 A user transaction that accesses memory optimized tables or natively compiled modules cannot access more… [41317_link1][51]
41922 The backup operation for a database with service-managed transaprent data encryption is not supported on… 41922_link1

[51]:

[35217_link1] :https://www.seangallardy.com/error-35217-and-availability-groups-smh/

Время прочтения
16 мин

Просмотры 36K

Привет, Хабр! Представляю вашему вниманию перевод статьи «Error and Transaction Handling in SQL Server. Part One – Jumpstart Error Handling» автора Erland Sommarskog.

1. Введение

Эта статья – первая в серии из трёх статей, посвященных обработке ошибок и транзакций в SQL Server. Её цель – дать вам быстрый старт в теме обработки ошибок, показав базовый пример, который подходит для большей части вашего кода. Эта часть написана в расчете на неопытного читателя, и по этой причине я намеренно умалчиваю о многих деталях. В данный момент задача состоит в том, чтобы рассказать как без упора на почему. Если вы принимаете мои слова на веру, вы можете прочесть только эту часть и отложить остальные две для дальнейших этапов в вашей карьере.

С другой стороны, если вы ставите под сомнение мои рекомендации, вам определенно необходимо прочитать две остальные части, где я погружаюсь в детали намного более глубоко, исследуя очень запутанный мир обработки ошибок и транзакций в SQL Server. Вторая и третья части, так же, как и три приложения, предназначены для читателей с более глубоким опытом. Первая статья — короткая, вторая и третья значительно длиннее.

Все статьи описывают обработку ошибок и транзакций в SQL Server для версии 2005 и более поздних версий.

1.1 Зачем нужна обработка ошибок?

Почему мы обрабатываем ошибки в нашем коде? На это есть много причин. Например, на формах в приложении мы проверяем введенные данные и информируем пользователей о допущенных при вводе ошибках. Ошибки пользователя – это предвиденные ошибки. Но нам также нужно обрабатывать непредвиденные ошибки. То есть, ошибки могут возникнуть из-за того, что мы что-то упустили при написании кода. Простой подход – это прервать выполнение или хотя бы вернуться на этап, в котором мы имеем полный контроль над происходящим. Недостаточно будет просто подчеркнуть, что совершенно непозволительно игнорировать непредвиденные ошибки. Это недостаток, который может вызвать губительные последствия: например, стать причиной того, что приложение будет предоставлять некорректную информацию пользователю или, что еще хуже, сохранять некорректные данные в базе. Также важно сообщать о возникновении ошибки с той целью, чтобы пользователь не думал о том, что операция прошла успешно, в то время как ваш код на самом деле ничего не выполнил.

Мы часто хотим, чтобы в базе данных изменения были атомарными. Например, задача по переводу денег с одного счета на другой. С этой целью мы должны изменить две записи в таблице CashHoldings и добавить две записи в таблицу Transactions. Абсолютно недопустимо, чтобы ошибки или сбой привели к тому, что деньги будут переведены на счет получателя, а со счета отправителя они не будут списаны. По этой причине обработка ошибок также касается и обработки транзакций. В приведенном примере нам нужно обернуть операцию в BEGIN TRANSACTION и COMMIT TRANSACTION, но не только это: в случае ошибки мы должны убедиться, что транзакция откачена.

2. Основные команды

Мы начнем с обзора наиболее важных команд, которые необходимы для обработки ошибок. Во второй части я опишу все команды, относящиеся к обработке ошибок и транзакций.

2.1 TRY-CATCH

Основным механизмом обработки ошибок является конструкция TRY-CATCH, очень напоминающая подобные конструкции в других языках. Структура такова:

BEGIN TRY
   <обычный код>
END TRY
BEGIN CATCH
   <обработка ошибок>
END CATCH

Если какая-либо ошибка появится в <обычный код>, выполнение будет переведено в блок CATCH, и будет выполнен код обработки ошибок.

Как правило, в CATCH откатывают любую открытую транзакцию и повторно вызывают ошибку. Таким образом, вызывающая клиентская программа понимает, что что-то пошло не так. Повторный вызов ошибки мы обсудим позже в этой статье.

Вот очень быстрый пример:

BEGIN TRY
   DECLARE @x int
   SELECT @x = 1/0
   PRINT 'Not reached'
END TRY
BEGIN CATCH 
   PRINT 'This is the error: ' + error_message()
END CATCH

Результат выполнения: This is the error: Divide by zero error encountered.

Мы вернемся к функции error_message() позднее. Стоит отметить, что использование PRINT в обработчике CATCH приводится только в рамках экспериментов и не следует делать так в коде реального приложения.

Если <обычный код> вызывает хранимую процедуру или запускает триггеры, то любая ошибка, которая в них возникнет, передаст выполнение в блок CATCH. Если более точно, то, когда возникает ошибка, SQL Server раскручивает стек до тех пор, пока не найдёт обработчик CATCH. И если такого обработчика нет, SQL Server отправляет сообщение об ошибке напрямую клиенту.

Есть одно очень важное ограничение у конструкции TRY-CATCH, которое нужно знать: она не ловит ошибки компиляции, которые возникают в той же области видимости. Рассмотрим пример:

CREATE PROCEDURE inner_sp AS
   BEGIN TRY
      PRINT 'This prints'
      SELECT * FROM NoSuchTable
      PRINT 'This does not print'
   END TRY
   BEGIN CATCH
      PRINT 'And nor does this print'
   END CATCH
go
EXEC inner_sp

Выходные данные:

This prints
Msg 208, Level 16, State 1, Procedure inner_sp, Line 4
Invalid object name 'NoSuchTable'

Как можно видеть, блок TRY присутствует, но при возникновении ошибки выполнение не передается блоку CATCH, как это ожидалось. Это применимо ко всем ошибкам компиляции, таким как пропуск колонок, некорректные псевдонимы и тому подобное, которые возникают во время выполнения. (Ошибки компиляции могут возникнуть в SQL Server во время выполнения из-за отложенного разрешения имен – особенность, благодаря которой SQL Server позволяет создать процедуру, которая обращается к несуществующим таблицам.)

Эти ошибки не являются полностью неуловимыми; вы не можете поймать их в области, в которой они возникают, но вы можете поймать их во внешней области. Добавим такой код к предыдущему примеру:

CREATE PROCEDURE outer_sp AS
   BEGIN TRY
      EXEC inner_sp
   END TRY
   BEGIN CATCH
      PRINT 'The error message is: ' + error_message()
   END CATCH
go
EXEC outer_sp

Теперь мы получим на выходе это:

This prints
The error message is: Invalid object name 'NoSuchTable'.

На этот раз ошибка была перехвачена, потому что сработал внешний обработчик CATCH.

2.2 SET XACT_ABORT ON

В начало ваших хранимых процедур следует всегда добавлять это выражение:

SET XACT_ABORT, NOCOUNT ON

Оно активирует два параметра сессии, которые выключены по умолчанию в целях совместимости с предыдущими версиями, но опыт доказывает, что лучший подход – это иметь эти параметры всегда включенными. Поведение SQL Server по умолчанию в той ситуации, когда не используется TRY-CATCH, заключается в том, что некоторые ошибки прерывают выполнение и откатывают любые открытые транзакции, в то время как с другими ошибками выполнение последующих инструкций продолжается. Когда вы включаете XACT_ABORT ON, почти все ошибки начинают вызывать одинаковый эффект: любая открытая транзакция откатывается, и выполнение кода прерывается. Есть несколько исключений, среди которых наиболее заметным является выражение RAISERROR.

Параметр XACT_ABORT необходим для более надежной обработки ошибок и транзакций. В частности, при настройках по умолчанию есть несколько ситуаций, когда выполнение может быть прервано без какого-либо отката транзакции, даже если у вас есть TRY-CATCH. Мы видели такой пример в предыдущем разделе, где мы выяснили, что TRY-CATCH не перехватывает ошибки компиляции, возникшие в той же области. Открытая транзакция, которая не была откачена из-за ошибки, может вызвать серьезные проблемы, если приложение работает дальше без завершения транзакции или ее отката.

Для надежной обработки ошибок в SQL Server вам необходимы как TRY-CATCH, так и SET XACT_ABORT ON. Среди них инструкция SET XACT_ABORT ON наиболее важна. Если для кода на промышленной среде только на нее полагаться не стоит, то для быстрых и простых решений она вполне подходит.

Параметр NOCOUNT не имеет к обработке ошибок никакого отношения, но включение его в код является хорошей практикой. NOCOUNT подавляет сообщения вида (1 row(s) affected), которые вы можете видеть в панели Message в SQL Server Management Studio. В то время как эти сообщения могут быть полезны при работе c SSMS, они могут негативно повлиять на производительность в приложении, так как увеличивают сетевой трафик. Сообщение о количестве строк также может привести к ошибке в плохо написанных клиентских приложениях, которые могут подумать, что это данные, которые вернул запрос.

Выше я использовал синтаксис, который немного необычен. Большинство людей написали бы два отдельных выражения:

SET NOCOUNT ON
SET XACT_ABORT ON

Между ними нет никакого отличия. Я предпочитаю версию с SET и запятой, т.к. это снижает уровень шума в коде. Поскольку эти выражения должны появляться во всех ваших хранимых процедурах, они должны занимать как можно меньше места.

3. Основной пример обработки ошибок

После того, как мы посмотрели на TRY-CATCH и SET XACT_ABORT ON, давайте соединим их вместе в примере, который мы можем использовать во всех наших хранимых процедурах. Для начала я покажу пример, в котором ошибка генерируется в простой форме, а в следующем разделе я рассмотрю решения получше.

Для примера я буду использовать эту простую таблицу.

CREATE TABLE sometable(a int NOT NULL,
                       b int NOT NULL,
                       CONSTRAINT pk_sometable PRIMARY KEY(a, b))

Вот хранимая процедура, которая демонстрирует, как вы должны работать с ошибками и транзакциями.

CREATE PROCEDURE insert_data @a int, @b int AS 
   SET XACT_ABORT, NOCOUNT ON
   BEGIN TRY
      BEGIN TRANSACTION
      INSERT sometable(a, b) VALUES (@a, @b)
      INSERT sometable(a, b) VALUES (@b, @a)
      COMMIT TRANSACTION
   END TRY
   BEGIN CATCH
      IF @@trancount > 0 ROLLBACK TRANSACTION
      DECLARE @msg nvarchar(2048) = error_message()  
      RAISERROR (@msg, 16, 1)
      RETURN 55555
   END CATCH

Первая строка в процедуре включает XACT_ABORT и NOCOUNT в одном выражении, как я показывал выше. Эта строка – единственная перед BEGIN TRY. Все остальное в процедуре должно располагаться после BEGIN TRY: объявление переменных, создание временных таблиц, табличных переменных, всё. Даже если у вас есть другие SET-команды в процедуре (хотя причины для этого встречаются редко), они должны идти после BEGIN TRY.

Причина, по которой я предпочитаю указывать SET XACT_ABORT и NOCOUNT перед BEGIN TRY, заключается в том, что я рассматриваю это как одну строку шума: она всегда должна быть там, но я не хочу, чтобы это мешало взгляду. Конечно же, это дело вкуса, и если вы предпочитаете ставить SET-команды после BEGIN TRY, ничего страшного. Важно то, что вам не следует ставить что-либо другое перед BEGIN TRY.

Часть между BEGIN TRY и END TRY является основной составляющей процедуры. Поскольку я хотел использовать транзакцию, определенную пользователем, я ввел довольно надуманное бизнес-правило, в котором говорится, что если вы вставляете пару, то обратная пара также должна быть вставлена. Два выражения INSERT находятся внутри BEGIN и COMMIT TRANSACTION. Во многих случаях у вас будет много строк кода между BEGIN TRY и BEGIN TRANSACTION. Иногда у вас также будет код между COMMIT TRANSACTION и END TRY, хотя обычно это только финальный SELECT, возвращающий данные или присваивающий значения выходным параметрам. Если ваша процедура не выполняет каких-либо изменений или имеет только одно выражение INSERT/UPDATE/DELETE/MERGE, то обычно вам вообще не нужно явно указывать транзакцию.

В то время как блок TRY будет выглядеть по-разному от процедуры к процедуре, блок CATCH должен быть более или менее результатом копирования и вставки. То есть вы делаете что-то короткое и простое и затем используете повсюду, не особо задумываясь. Обработчик CATCH, приведенный выше, выполняет три действия:

  1. Откатывает любые открытые транзакции.
  2. Повторно вызывает ошибку.
  3. Убеждается, что возвращаемое процедурой значение отлично от нуля.

Эти три действия должны всегда быть там. Мы можете возразить, что строка

IF @@trancount > 0 ROLLBACK TRANSACTION

не нужна, если нет явной транзакции в процедуре, но это абсолютно неверно. Возможно, вы вызываете хранимую процедуру, которая открывает транзакцию, но которая не может ее откатить из-за ограничений TRY-CATCH. Возможно, вы или кто-то другой добавите явную транзакцию через два года. Вспомните ли вы тогда о том, что нужно добавить строку с откатом? Не рассчитывайте на это. Я также слышу читателей, которые возражают, что если тот, кто вызывает процедуру, открыл транзакцию, мы не должны ее откатывать… Нет, мы должны, и если вы хотите знать почему, вам нужно прочитать вторую и третью части. Откат транзакции в обработчике CATCH – это категорический императив, у которого нет исключений.

Код повторной генерации ошибки включает такую строку:

DECLARE @msg nvarchar(2048) = error_message()

Встроенная функция error_message() возвращает текст возникшей ошибки. В следующей строке ошибка повторно вызывается с помощью выражения RAISERROR. Это не самый простой способ вызова ошибки, но он работает. Другие способы мы рассмотрим в следующей главе.

Замечание: синтаксис для присвоения начального значения переменной в DECLARE был внедрен в SQL Server 2008. Если у вас SQL Server 2005, вам нужно разбить строку на DECLARE и выражение SELECT.

Финальное выражение RETURN – это страховка. RAISERROR никогда не прерывает выполнение, поэтому выполнение следующего выражения будет продолжено. Пока все процедуры используют TRY-CATCH, а также весь клиентский код обрабатывает исключения, нет повода для беспокойства. Но ваша процедура может быть вызвана из старого кода, написанного до SQL Server 2005 и до внедрения TRY-CATCH. В те времена лучшее, что мы могли делать, это смотреть на возвращаемые значения. То, что вы возвращаете с помощью RETURN, не имеет особого значения, если это не нулевое значение (ноль обычно обозначает успешное завершение работы).

Последнее выражение в процедуре – это END CATCH. Никогда не следует помещать какой-либо код после END CATCH. Кто-нибудь, читающий процедуру, может не увидеть этот кусок кода.

После прочтения теории давайте попробуем тестовый пример:

EXEC insert_data 9, NULL

Результат выполнения:

Msg 50000, Level 16, State 1, Procedure insert_data, Line 12
Cannot insert the value NULL into column 'b', table 'tempdb.dbo.sometable'; column does not allow nulls. INSERT fails.

Давайте добавим внешнюю процедуру для того, чтобы увидеть, что происходит при повторном вызове ошибки:

CREATE PROCEDURE outer_sp @a int, @b int AS
   SET XACT_ABORT, NOCOUNT ON
   BEGIN TRY
      EXEC insert_data @a, @b
   END TRY
   BEGIN CATCH
      IF @@trancount > 0 ROLLBACK TRANSACTION
      DECLARE @msg nvarchar(2048) = error_message()
      RAISERROR (@msg, 16, 1)
      RETURN 55555
   END CATCH
go
EXEC outer_sp 8, 8

Результат работы:

Msg 50000, Level 16, State 1, Procedure outer_sp, Line 9
Violation of PRIMARY KEY constraint 'pk_sometable'. Cannot insert duplicate key in object 'dbo.sometable'. The duplicate key value is (8, 8).

Мы получили корректное сообщение об ошибке, но если вы посмотрите на заголовки этого сообщения и на предыдущее поближе, то можете заметить проблему:

Msg 50000, Level 16, State 1, Procedure insert_data, Line 12
Msg 50000, Level 16, State 1, Procedure outer_sp, Line 9

Сообщение об ошибке выводит информацию о расположении конечного выражения RAISERROR. В первом случае некорректен только номер строки. Во втором случае некорректно также имя процедуры. Для простых процедур, таких как наш тестовый пример, это не является большой проблемой. Но если у вас есть несколько уровней вложенных сложных процедур, то наличие сообщения об ошибке с отсутствием указания на место её возникновения сделает поиск и устранение ошибки намного более сложным делом. По этой причине желательно генерировать ошибку таким образом, чтобы можно было определить нахождение ошибочного фрагмента кода быстро, и это то, что мы рассмотрим в следующей главе.

4. Три способа генерации ошибки

4.1 Использование error_handler_sp

Мы рассмотрели функцию error_message(), которая возвращает текст сообщения об ошибке. Сообщение об ошибке состоит из нескольких компонентов, и существует своя функция error_xxx() для каждого из них. Мы можем использовать их для повторной генерации полного сообщения, которое содержит оригинальную информацию, хотя и в другом формате. Если делать это в каждом обработчике CATCH, это будет большой недостаток — дублирование кода. Вам не обязательно находиться в блоке CATCH для вызова error_message() и других подобных функций, и они вернут ту же самую информацию, если будут вызваны из хранимой процедуры, которую выполнит блок CATCH.

Позвольте представить вам error_handler_sp:

CREATE PROCEDURE error_handler_sp AS
 
   DECLARE @errmsg   nvarchar(2048),
           @severity tinyint,
           @state    tinyint,
           @errno    int,
           @proc     sysname,
           @lineno   int
           
   SELECT @errmsg = error_message(), @severity = error_severity(),
          @state  = error_state(), @errno = error_number(),
          @proc   = error_procedure(), @lineno = error_line()
       
   IF @errmsg NOT LIKE '***%'
   BEGIN
      SELECT @errmsg = '*** ' + coalesce(quotename(@proc), '<dynamic SQL>') + 
                       ', Line ' + ltrim(str(@lineno)) + '. Errno ' + 
                       ltrim(str(@errno)) + ': ' + @errmsg
   END
   RAISERROR('%s', @severity, @state, @errmsg)

Первое из того, что делает error_handler_sp – это сохраняет значение всех error_xxx() функций в локальные переменные. Я вернусь к выражению IF через секунду. Вместо него давайте посмотрим на выражение SELECT внутри IF:

SELECT @errmsg = '*** ' + coalesce(quotename(@proc), '<dynamic SQL>') + 
                 ', Line ' + ltrim(str(@lineno)) + '. Errno ' + 
                 ltrim(str(@errno)) + ': ' + @errmsg

Цель этого SELECT заключается в форматировании сообщения об ошибке, которое передается в RAISERROR. Оно включает в себя всю информацию из оригинального сообщения об ошибке, которое мы не можем вставить напрямую в RAISERROR. Мы должны обработать имя процедуры, которое может быть NULL для ошибок в обычных скриптах или в динамическом SQL. Поэтому используется функция COALESCE. (Если вы не понимаете форму выражения RAISERROR, я рассказываю о нем более детально во второй части.)

Отформатированное сообщение об ошибке начинается с трех звездочек. Этим достигаются две цели: 1) Мы можем сразу видеть, что это сообщение вызвано из обработчика CATCH. 2) Это дает возможность для error_handler_sp отфильтровать ошибки, которые уже были сгенерированы один или более раз, с помощью условия NOT LIKE ‘***%’ для того, чтобы избежать изменения сообщения во второй раз.

Вот как обработчик CATCH должен выглядеть, когда вы используете error_handler_sp:

BEGIN CATCH
   IF @@trancount > 0 ROLLBACK TRANSACTION
   EXEC error_handler_sp
   RETURN 55555
END CATCH

Давайте попробуем несколько тестовых сценариев.

EXEC insert_data 8, NULL
EXEC outer_sp 8, 8

Результат выполнения:

Msg 50000, Level 16, State 2, Procedure error_handler_sp, Line 20
*** [insert_data], Line 5. Errno 515: Cannot insert the value NULL into column 'b', table 'tempdb.dbo.sometable'; column does not allow nulls. INSERT fails.
Msg 50000, Level 14, State 1, Procedure error_handler_sp, Line 20
*** [insert_data], Line 6. Errno 2627: Violation of PRIMARY KEY constraint 'pk_sometable'. Cannot insert duplicate key in object 'dbo.sometable'. The duplicate key value is (8, 8).

Заголовки сообщений говорят о том, что ошибка возникла в процедуре error_handler_sp, но текст сообщений об ошибках дает нам настоящее местонахождение ошибки – как название процедуры, так и номер строки.

Я покажу еще два метода вызова ошибок. Однако error_handler_sp является моей главной рекомендацией для читателей, которые читают эту часть. Это — простой вариант, который работает на всех версиях SQL Server начиная с 2005. Существует только один недостаток: в некоторых случаях SQL Server генерирует два сообщения об ошибках, но функции error_xxx() возвращают только одну из них, и поэтому одно из сообщений теряется. Это может быть неудобно при работе с административными командами наподобие BACKUPRESTORE, но проблема редко возникает в коде, предназначенном чисто для приложений.

4.2. Использование ;THROW

В SQL Server 2012 Microsoft представил выражение ;THROW для более легкой обработки ошибок. К сожалению, Microsoft сделал серьезную ошибку при проектировании этой команды и создал опасную ловушку.

С выражением ;THROW вам не нужно никаких хранимых процедур. Ваш обработчик CATCH становится таким же простым, как этот:

BEGIN CATCH
   IF @@trancount > 0 ROLLBACK TRANSACTION
   ;THROW
   RETURN 55555
END CATCH

Достоинство ;THROW в том, что сообщение об ошибке генерируется точно таким же, как и оригинальное сообщение. Если изначально было два сообщения об ошибках, оба сообщения воспроизводятся, что делает это выражение еще привлекательнее. Как и со всеми другими сообщениями об ошибках, ошибки, сгенерированные ;THROW, могут быть перехвачены внешним обработчиком CATCH и воспроизведены. Если обработчика CATCH нет, выполнение прерывается, поэтому оператор RETURN в данном случае оказывается не нужным. (Я все еще рекомендую оставлять его, на случай, если вы измените свое отношение к ;THROW позже).

Если у вас SQL Server 2012 или более поздняя версия, измените определение insert_data и outer_sp и попробуйте выполнить тесты еще раз. Результат в этот раз будет такой:

Msg 515, Level 16, State 2, Procedure insert_data, Line 5
Cannot insert the value NULL into column 'b', table 'tempdb.dbo.sometable'; column does not allow nulls. INSERT fails.
Msg 2627, Level 14, State 1, Procedure insert_data, Line 6
Violation of PRIMARY KEY constraint 'pk_sometable'. Cannot insert duplicate key in object 'dbo.sometable'. The duplicate key value is (8, 8).

Имя процедуры и номер строки верны и нет никакого другого имени процедуры, которое может нас запутать. Также сохранены оригинальные номера ошибок.

В этом месте вы можете сказать себе: действительно ли Microsoft назвал команду ;THROW? Разве это не просто THROW? На самом деле, если вы посмотрите в Books Online, там не будет точки с запятой. Но точка с запятой должны быть. Официально они отделяют предыдущее выражение, но это опционально, и далеко не все используют точку с запятой в выражениях T-SQL. Более важно, что если вы пропустите точку с запятой перед THROW, то не будет никакой синтаксической ошибки. Но это повлияет на поведение при выполнении выражения, и это поведение будет непостижимым для непосвященных. При наличии активной транзакции вы получите сообщение об ошибке, которое будет полностью отличаться от оригинального. И еще хуже, что при отсутствии активной транзакции ошибка будет тихо выведена без обработки. Такая вещь, как пропуск точки с запятой, не должно иметь таких абсурдных последствий. Для уменьшения риска такого поведения, всегда думайте о команде как о ;THROW (с точкой с запятой).

Нельзя отрицать того, что ;THROW имеет свои преимущества, но точка с запятой не единственная ловушка этой команды. Если вы хотите использовать ее, я призываю вас прочитать по крайней мере вторую часть этой серии, где я раскрываю больше деталей о команде ;THROW. До этого момента, используйте error_handler_sp.

4.3. Использование SqlEventLog

Третий способ обработки ошибок – это использование SqlEventLog, который я описываю очень детально в третьей части. Здесь я лишь сделаю короткий обзор.

SqlEventLog предоставляет хранимую процедуру slog.catchhandler_sp, которая работает так же, как и error_handler_sp: она использует функции error_xxx() для сбора информации и выводит сообщение об ошибке, сохраняя всю информацию о ней. Вдобавок к этому, она логирует ошибку в таблицу splog.sqleventlog. В зависимости от типа приложения, которое у вас есть, эта таблица может быть очень ценным объектом.

Для использования SqlEventLog, ваш обработчик CATCH должен быть таким:

BEGIN CATCH
   IF @@trancount > 0 ROLLBACK TRANSACTION
   EXEC slog.catchhandler_sp @@procid
   RETURN 55555
END CATCH

@@procid возвращает идентификатор объекта текущей хранимой процедуры. Это то, что SqlEventLog использует для логирования информации в таблицу. Используя те же тестовые сценарии, получим результат их работы с использованием catchhandler_sp:

Msg 50000, Level 16, State 2, Procedure catchhandler_sp, Line 125
{515} Procedure insert_data, Line 5
Cannot insert the value NULL into column 'b', table 'tempdb.dbo.sometable'; column does not allow nulls. INSERT fails.
Msg 50000, Level 14, State 1, Procedure catchhandler_sp, Line 125
{2627} Procedure insert_data, Line 6
Violation of PRIMARY KEY constraint 'pk_sometable'. Cannot insert duplicate key in object 'dbo.sometable'. The duplicate key value is (8, 8).

Как вы видите, сообщение об ошибке отформатировано немного не так, как это делает error_handler_sp, но основная идея такая же. Вот образец того, что было записано в таблицу slog.sqleventlog:

logid logdate errno severity logproc linenum msgtext
1 2015-01-25 22:40:24.393 515 16 insert_data 5 Cannot insert …
2 2015-01-25 22:40:24.395 2627 14 insert_data 6 Violation of …

Если вы хотите попробовать SqlEventLog, вы можете загрузить файл sqleventlog.zip. Инструкция по установке находится в третьей части, раздел Установка SqlEventLog.

5. Финальные замечания

Вы изучили основной образец для обработки ошибок и транзакций в хранимых процедурах. Он не идеален, но он должен работать в 90-95% вашего кода. Есть несколько ограничений, на которые стоит обратить внимание:

  1. Как мы видели, ошибки компиляции не могут быть перехвачены в той же процедуре, в которой они возникли, а только во внешней процедуре.
  2. Пример не работает с пользовательскими функциями, так как ни TRY-CATCH, ни RAISERROR нельзя в них использовать.
  3. Когда хранимая процедура на Linked Server вызывает ошибку, эта ошибка может миновать обработчик в хранимой процедуре на локальном сервере и отправиться напрямую клиенту.
  4. Когда процедура вызвана как INSERT-EXEC, вы получите неприятную ошибку, потому что ROLLBACK TRANSACTION не допускается в данном случае.
  5. Как упомянуто выше, если вы используете error_handler_sp или SqlEventLog, мы потеряете одно сообщение, когда SQL Server выдаст два сообщения для одной ошибки. При использовании ;THROW такой проблемы нет.

Я рассказываю об этих ситуациях более подробно в других статьях этой серии.

Перед тем как закончить, я хочу кратко коснуться триггеров и клиентского кода.

Триггеры

Пример для обработки ошибок в триггерах не сильно отличается от того, что используется в хранимых процедурах, за исключением одной маленькой детали: вы не должны использовать выражение RETURN (потому что RETURN не допускается использовать в триггерах).

С триггерами важно понимать, что они являются частью команды, которая запустила триггер, и в триггере вы находитесь внутри транзакции, даже если не используете BEGIN TRANSACTION.
Иногда я вижу на форумах людей, которые спрашивают, могут ли они написать триггер, который не откатывает в случае падения запустившую его команду. Ответ таков: нет способа сделать это надежно, поэтому не стоит даже пытаться. Если в этом есть необходимость, по возможности не следует использовать триггер вообще, а найти другое решение. Во второй и третьей частях я рассматриваю обработку ошибок в триггерах более подробно.

Клиентский код

У вас должна быть обработка ошибок в коде клиента, если он имеет доступ к базе. То есть вы должны всегда предполагать, что при любом вызове что-то может пойти не так. Как именно внедрить обработку ошибок, зависит от конкретной среды.

Здесь я только обращу внимание на важную вещь: реакцией на ошибку, возвращенную SQL Server, должно быть завершение запроса во избежание открытых бесхозных транзакций:

IF @@trancount > 0 ROLLBACK TRANSACTION

Это также применимо к знаменитому сообщению Timeout expired (которое является не сообщением от SQL Server, а от API).

6. Конец первой части

Это конец первой из трех частей серии. Если вы хотели изучить вопрос обработки ошибок быстро, вы можете закончить чтение здесь. Если вы настроены идти дальше, вам следует прочитать вторую часть, где наше путешествие по запутанным джунглям обработки ошибок и транзакций в SQL Server начинается по-настоящему.

… и не забывайте добавлять эту строку в начало ваших хранимых процедур:

SET XACT_ABORT, NOCOUNT ON

Содержание статьи:

    • SQL-сервер не найден или недоступен, ошибки соединения с SQL-сервером
      • Ошибка SQL-сервера 26
      • Ошибка SQL-сервера 18456
      • Не удалось запустить SQL-server — код ошибки 3417
    • Повреждена база данных
      • Код ошибки SQL-сервера 945
      • Код ошибки SQL-сервера 5172
      • Ошибка SQL-сервера 823
      • Ошибка SQL-сервера 8946
    • Другие ошибки SQL Server
      • Код ошибки SQL-сервера 1814
      • Код ошибки SQL-сервера 1067
      • SQL-сервер запускается, но работает слишком медленно

SQL-сервер не найден или недоступен, ошибки соединения с SQL-сервером

  • Если SQL-сервер не найден, убедитесь, что ваш экземпляр SQL-сервера действительно установлен и запущен. Для этого зайдите на компьютер, где он установлен, запустите диспетчер конфигурации SQL и проверьте, есть ли там тот экземпляр, к которому вы пытаетесь подключиться и запущен ли он. Нелишним будет также получить отчет об обнаружении компонентов SQL-серверов.
  • Если вы проделали п1. и не обнаружили источник проблемы, возможно, неверно указан IP-адрес компьютера или номер порта TCP. Перепроверьте их настройки.
  • Причиной того, что невозможно подключиться к SQL-серверу, также может быть сеть, убедитесь, что компьютер с SQL-сервером доступен по сети.
  • Проверьте, может ли клиентское приложение, установленное на том же компьютере, что и сервер, подключиться к SQL-серверу. Запустите SQL Server Management Studio(SSMS), в диалоговом окне “Подключиться к серверу” выберите тип сервера Database Engine, укажите способ аутентификации “Аутентификация Windows”, введите имя компьютера и экземпляра SQL-сервера. Проверьте подключение.

Обратите внимание, что многие сообщения об ошибках могут быть не показаны или не содержат достаточной информации для устранения проблемы. Это сделано из соображений безопасности, чтобы при попытке взлома злоумышленники не могли получить информацию об SQL-сервере. Полные сведения содержатся в логе ошибок, который обычно хранится по адресу C:Program FilesMicrosoft SQL ServerMSSQL13.MSSQLSERVERMSSQLLogERRORLOG, или там, куда его поместил администратор системы.

Ошибка SQL-сервера 26

Одна из наиболее часто встречающихся ошибок подключения к SQL-серверу, обычно связана с тем, что в настройках SQL-сервера не разрешены или ограничены удаленные соединения. Чтобы это исправить, попробуйте:

  • в SSMS в настройках SQL-сервера включите аутентификацию Windows
  • для брандмауэра Windows  создайте новое правило, которое разрешает подключение для всех программ и протоколов с указанного IP-адреса
  • убедитесь, что запущена служба SQL Server Browser

Ошибка SQL-сервера 18456

Эта ошибка означает, что попытка подключиться к серверу не успешна из-за проблем с именем пользователя или паролем. По коду ошибки в журнале ошибок можно узнать более точную причину, чтобы устранить ее.

Не удалось запустить SQL-server — код ошибки 3417

Возникает в случае, если были изменены настройки Windows или перемещена папка с файлами MSSQL.

  • зайдите в C:Program FilesMicrosoft SQLServerMSSQL.1MSSqLData — БезопасностьНастройки доступа — Учетная запись сетевой службы — добавьте учетную запись сетевой службы
  • проверьте, что MDF-файл не сжимается. Если это не так, отключите “Сжимать содержимое для экономии места на диске” в свойствах файла

Иногда ни один из этих способов не помогает, это значит, что файлы БД повреждены и ее придется восстанавливать из резервной копии.

Повреждена база данных

Код ошибки SQL-сервера 945

Ошибка 945 возникает, когда БД SQL-сервера помечена как IsShutdown. Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД, файлы MDF и LDF не должны быть помечены “Только для чтения”.

Код ошибки SQL-сервера 5172

SQL-сервер хранит свою физическую БД в первичном файле, в котором информация разбита постранично. Первая страница содержит информацию о заголовке mdf-файла и называется страницей заголовка. Она состоит из разнообразной информации о БД, такой как размер файла, подпись и т.д. В процессе прикрепления MDF на SQL-сервере часто возникает ошибка 5172. Это в основном происходит, если MDF-файл поврежден, информация в его заголовке тоже и соответственно сложно добраться до данных. Причиной может быть вирус, аварийное выключение системы, ошибка оборудования.

Ошибка SQL-сервера 823

SQL использует API Windows для операций ввода-вывода, но кроме завершения этих операций SQL проверяет все ошибки обращений к API. Если эти обращения несовместимы с ОС, появляется ошибка 823. Сообщение об ошибке 823 означает, что существует проблема с базовым оборудованием для хранения данных или с драйвером, который находится на пути запроса ввода-вывода. Пользователи могут столкнуться с этой ошибкой, если в файловой системе есть противоречия или поврежден файл базы данных.

Ошибка SQL-сервера 8946

Основной причиной ошибки 8946 так же, как и для 5172, является повреждение заголовков страниц БД SQL вследствие сбоя питания, вирусной атаки, отказа оборудования — SQL-сервер больше не может прочесть эти страницы.

Перечисленные ошибки 945, 5172, 823, 8946 можно устранить двумя методами:

  • если у вас есть свежая резервная копия базы — восстановить базу из этой копии
  • можно попробовать использовать специализированное ПО, такое как SQL Recovery Tool, чтобы восстановить поврежденные файлы

Желательно определить, что именно привело к возникновению ошибок и принять меры, чтобы это не повторялось — заменить плохо работающее оборудование, повысить информационную безопасность.

Другие ошибки SQL

Код ошибки SQL-сервера 1814

SQL-сервер не может создать базу данных tempdb.  Убедитесь, что на выделенном под нее диске достаточно места и что у учетной записи хватает прав для записи в указанную директорию.

Код ошибки SQL-сервера 1067

Эта ошибка может возникать по разным причинам. Наиболее часто оказывается, что повреждены или отсутствуют конфигурационные файлы, SQL-сервер обращается к поврежденным системным файлам, ошибочные данные пользователя, нет информации про лицензию. В самых тяжелых случаях придется переустанавливать SQL-сервер. Но иногда помогает восстановление поврежденных файлов или изменение настроек SQL-сервера — вы можете создать новую учетную запись в домене и использовать ее для службы MSSQL.

SQL-сервер запускается, но работает слишком медленно

Проанализируйте журнал сервера, индексы (фрагментацию), запросы, задания, возможность взаимных блокировок.  Причин может быть масса.

Мы работаем с разными версиями SQL-сервера уже много лет, знакомы со всевозможными инструкциями SQL-сервера, видели самые разные варианты его настройки и использования на проектах у своих клиентов. В целом мы можем выделить четыре основных источника неполадок:

  • Индексы — причина проблем номер один. Неправильные индексы, отсутствующие индексы, слишком много индексов и подобное. Чаще всего при проблеме с индексами пользователи или администраторы базы данных не получают сообщения об ошибке, они просто видят, что база работает очень медленно и докопаться до причин бывает очень нелегко
  • изначально плохая архитектура сервера баз данных — ошибка, которую очень сложно и дорого исправлять на этапе, когда база уже используется
  • плохой код, в котором возможны блокировки и тупиковые места
  • использование конфигурации по умолчанию,

Если у вас не получается устранить ошибки сервера SQL-server самостоятельно, если они появляются снова и снова, то скорее всего в основе лежит одна из этих причин. В таком случае — если у вас произошла ошибка с SQL сервером, ваше ПО не видит SQL-сервер, либо нужно развернуть кластер SQL-серверов — вы всегда можете обратиться за консультацией и технической поддержкой к специалистам Интегруса, отправив заявку с сайта, написав на e-mail, либо позвонив в колл-центр нашей компании.

Присоединяйтесь к нам,

чтобы получать чек-листы, реальные кейсы, а также
обзоры сервисов раз в 2 недели.

Error Severity Description
1 10 Version date of last upgrade: 10/11/90.
21 10 Warning: Fatal error %d occurred at %S_DATE. Note the error and
time, and contact your system administrator.
53 10 An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 — Could not open a connection to SQL Server ) (.Net SqlClient Data Provider).
101 15 Query not allowed in Waitfor.
102 15 Incorrect syntax near ‘%.*ls’.
103 15 The %S_MSG that starts with ‘%.*ls’ is too long. Maximum length is
%d.
104 15 ORDER BY items must appear in the select list if the statement
contains a UNION operator.
105 15 Unclosed quotation mark before the character string ‘%.*ls’.
106 16 Too many table names in the query. The maximum allowable is %d.
107 15 The column prefix ‘%.*ls’ does not match with a table name or
alias name used in the query.
108 15 The ORDER BY position number is out of range of the number of
items in the select list.
109 15 There are more columns in the INSERT statement
than values specified in the VALUES clause. The number of values in the VALUES
clause must match the number of columns specified in the INSERT statement.
110 15 There are fewer columns in the INSERT statement
than values specified in the VALUES clause.  The number of values in the
VALUES clause must match the number of columns specified in the INSERT
statement.
111 15 ‘CREATE FUNCTION’ must be the first statement in a query batch.
112 15 Variables are not allowed in the %ls statement.
113 15 Missing end comment mark ‘*/’.
114 15 Browse mode is invalid for a statement that assigns values to a
variable.
115 15 The FOR UPDATE clause is invalid for statements containing set operators.
116 15 Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS.
117 15 The object name «Object Name» contains more than the maximum number of
prefixes.  The maximum is 2.
118 15 Only members of the sysadmin role can specify the %ls option for
the %ls statement.
119 15 Must pass parameter number %d and subsequent parameters as ‘@name
= value’. After the form ‘@name = value’ has been used, all subsequent
parameters must be passed in the form ‘@name = value’.
120 15 The select list for the INSERT statement
contains fewer items than the insert list. The number of SELECT values must
match the number of INSERT columns.
121 15 The select list for the INSERT statement
contains more items than the insert list. The number of SELECT values must
match the number of INSERT columns.
122 15 The %ls option is allowed only with %ls syntax.
123 15 Batch/procedure exceeds maximum length of %d characters.
124 15 CREATE PROCEDURE contains no statements.
125 15 Case expressions may only be nested to level %d.
126 15 Invalid pseudocolumn «%.*ls».
127 15 A TOP N value may not be negative.
128 15 The name ‘<Column Name>’ is not permitted in this context. Only constants,
expressions, or variables allowed here. Column names are not permitted.
129 15 Fillfactor %d is not a valid percentage; fillfactor must be
between 1 and 100.
130 16 Cannot perform an aggregate function on an expression containing
an aggregate or a subquery.
131 15

The size (<Data Type Size>) given to the type ‘varchar / char / nvarchar / nchar / binary / varbinary’ exceeds the maximum allowed for any data type (8000).

The size (<Data Type Size>) given to the column ‘<Column Name>’ exceeds the maximum allowed for any data type (8000).

132 15 The label ‘%.*ls’ has already been declared. Label names must be
unique within a query batch or stored procedure.
133 15 A GOTO statement references the label ‘<Label Name>’ but the label has
not been declared.
134 15 The variable name ‘%.*ls’ has already been declared. Variable
names must be unique within a query batch or stored procedure.
135 15 Cannot use a BREAK statement outside the scope of a WHILE
statement.
136 15 Cannot use a CONTINUE statement outside the scope of a WHILE
statement.
137 15 Must declare the scalar variable ‘<Variable Name>’.
138 15 Correlation clause in a subquery not permitted.
139 15 Cannot assign a default value to a local variable.
140 15 Can only use IF UPDATE within a CREATE TRIGGER statement.
141 15 A SELECT statement that assigns a value to a
variable must not be combined with data-retrieval operations.
142 15 Incorrect syntax for definition of the ‘%ls’ constraint.
143 15 A COMPUTE BY item was not found in the order by list. All
expressions in the compute by list must also be present in the order by list.
144 15 Cannot use an aggregate or a subquery in an expression used for
the group by list of a GROUP BY clause.
145 15 ORDER BY items must appear in the select list
if SELECT DISTINCT is specified.
146 15 Could not allocate ancillary table for a subquery. Maximum number
of tables in a query (%d) exceeded.
147 15 An aggregate may not appear in the WHERE clause unless it is in a
subquery contained in a HAVING clause or a select list, and the column being
aggregated is an outer reference.
148 15 Incorrect time syntax in time string ‘<Wait Time>’ used with WAITFOR.
149 15 Time value ‘%.*ls’ used with WAITFOR is not a valid value. Check
date/time syntax.
150 15 Both terms of an outer join must contain columns.
151 15 ‘%.*ls’ is an invalid money value.
152 15 The same large data placement option «%.*ls» has been specified twice.
153 15 Invalid usage of the option %.*ls in the %ls statement.
154 15 a COMPUTE clause is not allowed in a SELECT INTO statement.
155 15 ‘<DATEADD option>’ is not a recognized DATEADD option.
156 15 Incorrect syntax near the keyword ‘%.*ls’.
157 15 An aggregate may not appear in the set list of an UPDATE
statement.
158 15 An aggregate may not appear in the OUTPUT clause.
159 15 SQL Server 2005, SQL Server 2008 — Must specify the table name and index name for the DROP INDEX statement.
SQL Server 2000 — For DROP INDEX, you must give both the table and the index name, in the form tablename.indexname.
160 15 Rule does not contain a variable.
161 15 Rule contains more than one variable.
162 15 Invalid expression in the TOP clause.
163 15 The compute by list does not match the order by list.
164 15 Each GROUP BY expression must contain at least one column that is not an outer reference.
GROUP BY expressions must refer to column names that appear in the
select list.
165 16 Privilege %ls may not be granted or revoked.
166 15 ‘CREATE VIEW’ does not allow specifying the
database name as a prefix to the object name.
167 16 Cannot create a trigger on a temporary object.
168 15 The %S_MSG ‘%.*ls’ is out of the range of computer representation
(%d bytes).
169 15 A column has been specified more than once in the order by list.
Columns in the order by list must be unique.
170 15 Line %d: Incorrect syntax near ‘%.*ls’.
171 15 Cannot use SELECT INTO in browse mode.
172 15 Cannot use HOLDLOCK in browse mode.
173 15 The definition for column <Column Name> must include a data type.
174 15 The dateadd function requires 3 arguments.
175 15 An aggregate may not appear in a computed column expression or check constraint.
176 15 The FOR BROWSE clause is no longer supported in views. Set the database compatibility level to 80 or lower for this statement to be allowed.
177 15 The IDENTITY function can only be used when the SELECT statement
has an INTO clause.
178 15 A RETURN statement with a return value cannot be used in this
context.
179 15 Cannot use the OUTPUT option when passing a constant to a stored
procedure.
180 15 There are too many parameters in this %ls statement. The maximum
number is %d.
181 15 SQL Server 2008 — Cannot use the OUTPUT option in a DECLARE, CREATE AGGREGATE or CREATE FUNCTION statement.
SQL Server 2005 — Cannot use the OUTPUT option in a DECLARE or CREATE FUNCTION statement.
SQL Server 2000 — Cannot use the OUTPUT option in a DECLARE statement.
182 15 Table and column names must be supplied for the READTEXT or
WRITETEXT utility.
183 15 The scale (<Scale Value>) for column ‘<Column Name>’ must be within the range 0 to <Precision Value>.
184 15 DEFAULT cannot be specified more than once for filegroups of the same content type.
185 15 Data stream is invalid for WRITETEXT statement in bulk form.
186 15 Data stream missing from WRITETEXT statement.
187 16 The valid range for MAX_QUEUE_READERS is 0 to 32767.
188 15 Cannot specify a log device in a CREATE DATABASE statement without
also specifying at least one non-log device.
189 15 The %ls function requires %d to %d arguments.
190 15 An invalid date or time was specified in the statement.
191 15 Some part of your SQL statement is nested too deeply. Rewrite the
query or break it up into smaller queries.
192 16 The scale must be less than or equal to the precision.
193 15 The object or column name starting with ‘%.*ls’ is too long. The
maximum length is %d characters.
194 15 A SELECT INTO statement cannot contain a SELECT statement that
assigns values to a variable.
195 15 ‘Function Name’ is not a recognized function name.
196 15 SELECT INTO must be the first query in an SQL statement containing
a UNION, INTERSECT or EXCEPT operator.
197 15 EXECUTE cannot be used as a source when inserting into a table
variable.
198 15 Browse mode is invalid for statements containing a UNION operator.
199 15 An INSERT statement cannot contain a SELECT statement that assigns
values to a variable.
201 16 Procedure ‘<Procedure Name>’ expects parameter ‘<Parameter Name>’, which was not
supplied.
202 16 Invalid type ‘%s’ for WAITFOR. Supported data types are
CHAR/VARCHAR, NCHAR/NVARCHAR, and DATETIME. WAITFOR DELAY supports the INT and
SMALLINT data types.
203 16 The name ‘%.*ls’ is not a valid identifier.
204 20 Normalization error in node %ls.
205 16 All queries in an SQL statement containing a
UNION operator must have an equal number of expressions in their target lists.
206 16 Operand type clash: %ls is incompatible with %ls
207 16 Invalid column name ‘%.*ls’.
208 16 Invalid object name ‘%.*ls’.
209 16 Ambiguous column name ‘%.*ls’.
210 16 Syntax error converting datetime from binary/varbinary string.
211 12 SyntaxPossible schema corruption. Run DBCC CHECKCATALOG.
212 16 Expression result length exceeds the maximum. %d max, %d found.
213 16 Insert Error: Column name or number of supplied
values does not match table definition.
214 16 Procedure expects parameter ‘%ls’ of type ‘%ls’.
215 16 Parameters supplied for object ‘%.*ls’ which is not a function. If the parameters are intended as a table hint, a WITH keyword is required.
216 16 Parameters were not supplied for the function ‘%.*ls’.
217 16 Maximum stored procedure, function, trigger, or view nesting level
exceeded (limit %d).
218 16 Could not find the type ‘%.*ls’. Either it does not exist or you do not have the necessary permission.
219 16 The type ‘%.*ls’ already exists, or you do not have permission to create it.
220 16 Arithmetic overflow error for data type %ls, value = %ld.
221 10 FIPS Warning: Implicit conversion from %ls to %ls.
222 16 The base type «%.*ls» is not a valid base type for the alias data type.
223 11 Object ID %ld specified as a default for table ID %ld, column ID
%d is missing or not of type default.
224 11 Object ID %ld specified as a rule for table ID %ld, column ID %d
is missing or not of type default.
225 16 The parameters supplied for the %ls «%.*ls» are not valid.
226 16 %ls statement not allowed within multi-statement transaction.
227 15 %.*ls is not a valid function, property, or field.
228 15 Method ‘%.*ls’ of type ‘%.*ls’ in assembly ‘%.*ls’ does not return any value.
229 14 %ls permission denied on object ‘%.*ls’, database ‘%.*ls’, owner
‘%.*ls’.
230 14 %ls permission denied on column ‘%.*ls’ of object ‘%.*ls’,
database ‘%.*ls’, owner ‘%.*ls’.
231 11 No such default. ID = %ld, database ID = %d.
232 16 Arithmetic overflow error for type %ls, value = %f.
233 16 The column ‘%.*ls’ in table ‘%.*ls’ cannot be null.
234 16 There is insufficient result space to convert a money value to
varchar / nvarchar / char / nchar.
235 16 Cannot convert a char value to money. The char value has incorrect
syntax.
236 16 The conversion from char data type to money resulted in a money
overflow error.
237 16 There is insufficient result space to convert a money value to
int / smallint / tinyint.
238 16 There is insufficient result space to convert the %ls value (= %d)
to the money data type.
239 16 Duplicate common table expression name ‘%.*ls’ was specified.
240 16 Types don’t match between the anchor and the recursive part in column «<Column Name>» of recursive query «<Recursive CTE>».
241 16 Syntax error converting datetime from character string.
242 16 The conversion of a char data type to a
datetime data type resulted in an out-of-range datetime value.
243 16 Type <Data Type> is not a defined system type.
244 16 The conversion of the %ls value ‘%.*ls’ overflowed an %hs column.
Use a larger integer column.
245 16 Syntax error converting the varchar value to a
column of data type int.
246 16 No anchor member was specified for recursive query «%.*ls».
247 16 An anchor member was found in the recursive part of recursive query «%.*ls».
248 16 The conversion of the %ls value ‘%.*ls’ overflowed an int column.
Maximum integer value exceeded.
249 16 The type «%ls» is not comparable. It cannot be used in the %ls clause.
Error Severity Description
251 16 Could not allocate ancillary table for query optimization. Maximum
number of tables in a query (%d) exceeded.
252 16 Recursive common table expression ‘<Common Table Expression Name>’ does not contain a top-level UNION ALL operator.
253 16 Recursive member of a common table expression ‘<Common Table Expression Name>’ has multiple recursive references.
254 16 Prefixed columns are not allowed in the column list of a PIVOT operator.
255 16 Pseudocolumns are not allowed in the column list of a PIVOT operator.
256 16 The data type int is invalid for the substring
function.  Allowed types are: char/varchar, nchar/nvarchar, and
binary/varbinary.
257 16 Implicit conversion from data type %ls to %ls is not allowed. Use
the CONVERT function to run this query.
258 16 Cannot call methods on %ls.
259 16 Ad hoc updates to system catalogs are not enabled. The system
administrator must reconfigure SQL Server to allow this.
260 16 Disallowed implicit conversion from data type %ls to data type
%ls, table ‘%.*ls’, column ‘%.*ls’. Use the CONVERT function to run this query.
261 16 ‘%.*ls’ is not a recognized function.
262 16 %ls permission denied in database ‘%.*ls’.
263 16 Must specify table to select from.
264 16 Column name ‘%.*ls’ appears more than once in the result column
list.
265 16 The column name «%.*ls» specified in the %ls operator conflicts with the existing column name in the %ls argument.
266 16 Transaction count after EXECUTE indicates that a COMMIT or
ROLLBACK TRANSACTION statement is missing. Previous count = %ld, current count
= %ld.
267 16 Object ‘%.*ls’ cannot be found.
268 16 Cannot run SELECT INTO in this database. The database owner must
run sp_dboption to enable this option.
270 16 Object ‘%.*ls’ cannot be modified.
271 16 SQL Server 2005, SQL Server 2008, SQL Server 2012 — The column ‘<Column Name>’ cannot be modified because it is either a computed column or is the result of a UNION operator.
SQL Server 2000 — Column ‘<Column Name>’ cannot be modified because it is a computed column.
272 16 Cannot update a timestamp column.
273 16 Cannot insert a non-null value into a timestamp column. Use INSERT
with a column list or with a default of NULL for the timestamp column.
275 16 Prefixes are not allowed in value or pivot columns of an UNPIVOT operator.
276 16 Pseudocolumns are not allowed as value or pivot columns of an UNPIVOT operator.
277 16 The column «%.*ls» is specified multiple times in the column list of the UNPIVOT operator.
278 16 The text, ntext, and image data types cannot be used in a GROUP BY
clause.
279 16 The text, ntext, and image data types are invalid in this subquery
or aggregate expression.
280 16 Only text, ntext, and image columns are valid with the TEXTPTR
function.
281 16 <Style number> is not a valid style number when converting from %ls to a
character string.
282 10 The ‘%.*ls’ procedure attempted to return a status of NULL, which
is not allowed. A status of 0 will be returned instead.
283 16 READTEXT cannot be used on inserted or deleted tables within an
INSTEAD OF trigger.
284 16 Rules cannot be bound to text, ntext, or image data types.
285 16 The READTEXT, WRITETEXT, and UPDATETEXT statements cannot be used
with views or functions.
286 16 The logical tables INSERTED and DELETED cannot be updated.
287 16 The %ls statement is not allowed within a trigger.
288 16 The PATINDEX function operates on char, nchar, varchar, nvarchar,
text, and ntext data types only.
290 16 Invalid EXECUTE statement using object «%ls», method «%ls».
291 16 CAST or CONVERT: invalid attributes specified for type ‘%.*ls’
292 16 There is insufficient result space to convert a smallmoney value
to varchar/nvarchar.
293 16 Cannot convert char value to smallmoney. The char value has
incorrect syntax.
294 16 The conversion from char data type to smallmoney data type
resulted in a smallmoney overflow error.
295 16 Syntax error converting character string to smalldatetime data
type.
296 16 The conversion of char data type to smalldatetime data type
resulted in an out-of-range smalldatetime value.
297 16 The user does not have permission to perform this action.
298 16 The conversion from datetime data type to smalldatetime data type
resulted in a smalldatetime overflow error.
299 16 The DATEADD function was called with bad type %ls.
300 14 %ls permission was denied on object ‘%.*ls’, database ‘%.*ls’.
301 16 Query contains an outer-join request that is not permitted.
302 16 The newsequentialid() built-in function can only be used in a DEFAULT expression for a column of type ‘uniqueidentifier’ in a CREATE TABLE or ALTER TABLE statement. It cannot be combined with other operators to form a complex scalar expression.
303 16 The table ‘%.*ls’ is an inner member of an outer-join clause. This
is not allowed if the table also participates in a regular join clause.
304 16 ‘%d’ is out of range for index option ‘%.*ls’. See sp_configure option ‘%ls’ for valid values.
305 16 The XML data type cannot be compared or sorted, except when using the IS NULL operator.
306 16 The text, ntext, and image data types cannot be compared or
sorted, except when using IS NULL or LIKE operator.
307 16 Index ID %d on table ‘%.*ls’ (specified in the FROM clause) does
not exist.
308 16 Index ‘%.*ls’ on table ‘%.*ls’ (specified in the FROM clause) does
not exist.
309 16 Cannot use index «%.*ls» on table «%.*ls» in a hint. XML indexes are not allowed in hints.
310 16 The value <MAXRECURSION value> specified for the MAXRECURSION option exceeds the allowed maximum of %d.
311 16 Cannot use text, ntext, or image columns in the ‘inserted’ and
‘deleted’ tables.
312 16 Cannot reference text, ntext, or image columns in a filter stored
procedure.
313 16 An insufficient number of arguments were
supplied for the procedure or function %.*ls.
314 16 Cannot use GROUP BY ALL with the special tables INSERTED or DELETED.
315 16 Index «%.*ls» on table «%.*ls» (specified in the FROM clause) is disabled or resides in a filegroup which is not online.
316 16 The index ID %d on table «%.*ls» (specified in the FROM clause) is disabled or resides in a filegroup which is not online.
317 16 Table-valued function ‘<Function Name>’ cannot have a column alias.
318 16 The table (and its columns) returned by a table-valued method need to be aliased.
319 16 Incorrect syntax near the keyword ‘with’. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
320 16 The compile-time variable value for ‘%.*ls’ in the OPTIMIZE FOR clause must be a literal.
321 15 %.*ls is not a recognized table hints option. If it is intended as a parameter to a table-valued function or to the CHANGETABLE function, ensure that your database compatibility mode is set to 90.
322 16 The variable «%.*ls» is specified in the OPTIMIZE FOR clause, but is not used in the query.
323 16 The ‘COMPUTE’ clause is not allowed in a statement containing an INTERSECT or EXCEPT operator.
324 15 The ‘ALL’ version of the %.*ls operator is not supported.
325 15 Incorrect syntax near ‘%.*ls’. You may need to set the compatibility level of the current database to a higher value to enable this feature. See help for the SET COMPATIBILITY_LEVEL option of ALTER DATABASE.
326 16 Multi-part identifier ‘%.*ls’ is ambiguous. Both columns ‘%.*ls’ and ‘%.*ls’ exist.
327 16 Function call ‘%.*ls’ is ambiguous: both a user-defined function and a method call with this name exist.
328 16 A cursor plan could not be generated for the given statement because the textptr() function was used on a LOB column from one of the base tables.
329 16 Each GROUP BY expression must contain at least one column reference.
330 15 The target ‘<Object Name>’ of the OUTPUT INTO clause cannot be a view or common table expression.
331 15 The target table ‘<Table Name>’ of the OUTPUT INTO clause cannot have any enabled triggers.
332 15 The target table ‘<Table Name>’ of the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship. Found reference constraint ‘<Primary Key or Foreign Key Constraint Name>’.
333 15 The target table ‘<Table Name>’ of the OUTPUT INTO clause cannot have any enabled check constraints or any enabled rules. Found check constraint or rule ‘<CHECK Constraint Name>’.
334 15 The target table ‘<Table Name>’ of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.
335 16 Function call cannot be used to match a target table in the FROM clause of a DELETE or UPDATE statement. Use function name ‘%.*ls’ without parameters instead.
336 15 Incorrect syntax near ‘%.*ls’. If this is intended to be a common table expression, you need to explicitly terminate the previous statement with a semi-colon.
337 10 Warning: the floating point value ‘%.*ls’ is too small. It will be interpreted as 0.
338 16 READEXT, WRITETEXT, and UPDATETEXT statements cannot be used with views, remote tables, and inserted or deleted tables inside triggers.
339 16 DEFAULT or NULL are not allowed as explicit identity values.
340 16 Cannot create the trigger «%.*ls» on view «%.*ls». AFTER triggers cannot be created on views.
341 16 Replication filter procedures may not contain columns of large object, large value, XML or CLR type.
342 16 Column «%.*ls» is not allowed in this context, and the user-defined function or aggregate «%.*ls» could not be found.
343 16 Unknown object type ‘%.*ls’ used in a CREATE, DROP, or ALTER statement.
344 16 Remote function reference ‘%.*ls’ is not allowed, and the column name ‘%.*ls’ could not be found or is ambiguous.
345 16 Function ‘%.*ls’ is not allowed in the OUTPUT clause, because it performs user or system data access, or is assumed to perform this access. A function is assumed by default to perform data access if it is not schemabound.
346 15 The parameter «<Parameter Name>» can not be declared READONLY since it is not a table-valued parameter.
347 16 The table-valued parameter «%.*ls» cannot be declared as an OUTPUT parameter.
348 16 The table variable «%.*ls» can not be passed to a stored procedure with the OUTPUT option.
349 16 The procedure «%.*ls» has no parameter named «%.*ls».
350 16 The column «%.*ls» does not have a valid data type. A column cannot be of a user-defined table type.
351 16 Column, parameter, or variable %.*ls. : Cannot find data type %.*ls.
352 15 The table-valued parameter «%.*ls» must be declared with the READONLY option.
353 16 Function ‘%.*ls’ is not allowed in the %S_MSG clause when the FROM clause contains a nested INSERT, UPDATE, DELETE, or MERGE statement. This is because the function performs user or system data access, or is assumed to perform this access. By default, a function is assumed to perform data access if it is not schema-bound.
354 15 The target ‘%.*ls’ of the INSERT statement cannot be a view or common table expression when the FROM clause contains a nested INSERT, UPDATE, DELETE, or MERGE statement.
355 15 The target table ‘<Table Name>’ of the INSERT statement cannot have any enabled triggers when the FROM clause contains a nested INSERT, UPDATE, DELETE, or MERGE statement.
356 15 The target table ‘%.*ls’ of the INSERT statement cannot be on either side of a (primary key, foreign key) relationship when the FROM clause contains a nested INSERT, UPDATE, DELETE, or MERGE statement. Found reference constraint ‘%ls’.
357 15 The target table ‘%.*ls’ of the INSERT statement cannot have any enabled rules when the FROM clause contains a nested INSERT, UPDATE, DELETE, or MERGE statement. Found rule ‘%ls’.
358 15 The target table ‘%.*ls’ of the MERGE statement cannot have any enabled rules. Found rule ‘%ls’.
359 15 The target ‘%.*ls’ of an OUTPUT INTO clause has an index with the ignore_dup_key option and cannot be used when an OUTPUT clause is also used.
360 15 The target column list of an INSERT, UPDATE, or MERGE statement cannot contain both a sparse column and the column set that contains the sparse column. Rewrite the statement to include either the sparse column or the column set, but not both.
361 16 The number of target columns that are specified in an INSERT, UPDATE, or MERGE statement exceeds the maximum of %d. This total number includes identity, timestamp, and columns that have default values. To correct this error, change the query to target a sparse column set instead of single sparse columns.
362 16 The query processor could not produce a query plan because the name ‘%.*ls’ in the FORCESEEK hint on table or view ‘<Object Name>’ did not match the key column names of the index ‘<Index Name>’.
363 16 The query processor could not produce a query plan because the FORCESEEK hint on table or view ‘<Object Name>’ cannot be used with the %S_MSG specified by index ‘%.*ls’.
364 16 The query processor could not produce a query plan because the FORCESEEK hint on view ‘<View Name>’ is used without a NOEXPAND hint. Resubmit the query with the NOEXPAND hint or remove the FORCESEEK hint on the view.
365 16 The query processor could not produce a query plan because the FORCESEEK hint on table or view ‘<Object Name>’ specified more seek columns than the number of key columns in index ‘%.*ls’.
366 16 The query processor could not produce a query plan because the FORCESEEK hint on table or view ‘<Object Name>’ cannot be used with the column store index ‘%.*ls’.
401 16 Unimplemented statement or expression %ls.
402 16 The data types %s and %s are incompatible in the %s operator.
403 16 Invalid operator for data type. Operator equals
add, type equals text.
404 16 The column reference «inserted.%.*ls» is not allowed because it refers to a base table that is not being modified in this statement.
405 16 A remote table cannot be used as a DML target in a statement which includes an OUTPUT clause or a nested DML statement.
406 16 %ls cannot be used in the PIVOT operator because it is not invariant to NULLs.
407 16 Internal error. The string routine in file %hs, line %d failed with HRESULT 0x%x.
408 16 A constant expression was encountered in the ORDER BY list, position %i.
409 16 The %ls operation cannot take a %ls data type as an argument.
410 20 COMPUTE clause #%d ‘BY’ expression #%d is not in the order by
list.
411 16 COMPUTE clause #%d, aggregate expression #%d is not in the select
list.
412 16 The column «%.*ls» is not updatable because it is derived or constant.
413 16 Correlated parameters or sub-queries are not supported by the inline function «%.*ls».
414 16 UPDATE is not allowed because the statement updates view «%.*ls» which participates in a join and has an INSTEAD OF UPDATE trigger.
415 16 DELETE is not allowed because the statement updates view «%.*ls» which participates in a join and has an INSTEAD OF DELETE trigger.
416 16 The service queue «%.*ls» cannot be directly updated.
417 16 TOP is not allowed in an UPDATE or DELETE statement against a partitioned view.
418 16 Objects exposing CLR type columns are not allowed in distributed queries. Use a pass-through query to access the remote object ‘%.*ls’.
420 16 The text, ntext, and image data types cannot be used in an ORDER
BY clause.
421 16 The text/ntext/image data type cannot be selected as DISTINCT because it is not comparable.
422 16 Common table expression defined but not used.
423 16 Xml data type methods are not supported in check constraints. Create a scalar user-defined function to wrap the method invocation. The error occurred at table «%.*ls».
424 16 Xml data type methods are not supported in computed column definitions of table variables and return tables of table-valued functions. The error occurred at column «%.*ls», table «%.*ls», in the %ls statement.
425 16 Data type %ls of receiving variable is not equal to the data type
%ls of column ‘%.*ls’.
426 16 The length %d of the receiving variable is less than the length %d
of the column ‘%.*ls’.
427 20 Could not load sysprocedures entries for constraint ID %d in
database ID %d.
428 20 Could not find row in sysconstraints for constraint ID %d in
database ID %d.
429 20 Could not find new constraint ID %d in sysconstraints, database ID
%d, at compile time.
430 20 Could not resolve table name for object ID %d, database ID %d,
when compiling foreign key.
431 19 Could not bind foreign key constraint. Too many tables involved in
the query.
432 16 Xml data type methods are not supported in check constraints anymore. Please drop the constraint or create a scalar user-defined function to wrap the method invocation. The error occurred at table «%.*ls».
433 20 Could not find CHECK constraint for ‘%.*ls’, although the table is
flagged as having one.
434 16 Function ‘%ls’ is not allowed in the OUTPUT clause.
435 16 Xml data type methods are not supported in computed column definitions. Create a scalar user-defined function to wrap the method invocation. The error occurred at column «%.*ls», table «%.*ls», in the %ls statement.
436 20 Could not open referenced table ID %d in database ID %d.
437 20 Could not resolve the referenced column name in table ID %d.
438 20 Could not resolve the referencing column name in table ID %d.
439 20 Could not find FOREIGN KEY constraints for table ‘%.*ls’ in
database ID %d although the table is flagged as having them.
440 16 Internal query compilation error. The stack overflow could not be handled.
441 16 Cannot use the ‘%ls’ function on a remote data source.
442 16 The NEST argument must be a column reference. Expressions are not allowed.
443 16 Invalid use of ‘getdate’ within a
function.
Invalid use of ‘INSERT’ within a function.
Invalid use of ‘UPDATE’ within a function.
444 16 Select statements included within a function cannot return data to
a client.
445 16 COLLATE clause cannot be used on expressions containing a COLLATE
clause.
446 16 Cannot resolve collation conflict for %ls operation.
447 16 Expression type %ls is invalid for COLLATE clause.
448 16 Invalid collation ‘%.*ls’.
449 16 Collation conflict caused by collate clauses with different
collation ‘%.*ls’ and ‘%.*ls’.
450 16 Code page translations are not supported for the text data type.
From: %d To: %d.
451 16 Cannot resolve collation conflict for column %d in %ls statement.
452 16 COLLATE clause cannot be used on user-defined data types.
453 16 Collation ‘%.*ls’ is supported on Unicode data types only and
cannot be set at the database or server level.
454 16 The UNNEST argument must be a nested table column.
455 16 The last statement included within a function
must be a return statement.
456 16 Implicit conversion of %ls value to %ls cannot be performed
because the resulting collation is unresolved due to collation conflict.
457 16 Implicit conversion of %ls value to %ls cannot be performed
because the collation of the value is unresolved due to a collation conflict.
458 16 Cannot create the SELECT INTO target table «%.*ls» because the xml column «%.*ls» is typed with a schema collection «%.*ls» from database «%.*ls». Xml columns cannot refer to schemata across databases.
459 16 Collation ‘%.*ls’ is supported on Unicode data types only and cannot be applied to char, varchar or text data types.
460 16 DISTINCT operator is not allowed in the recursive part of a recursive common table expression ‘<Common Table Expression Name>’.
461 16 TOP operator is not allowed in the recursive part of a recursive common table expression ‘<Common Table Expression Name>’.
462 16 Outer join is not allowed in the recursive part of a recursive common table expression ‘<Common Table Expression Name>’.
463 16 Functions with parameters are not allowed in the recursive part of a recursive common table expression ‘%.*ls’.
464 16 Functions with side effects are not allowed in the recursive part of a recursive common table expression ‘%.*ls’.
465 16 Recursive references are not allowed in subqueries.
466 16 UNION operator is not allowed in the recursive part of a recursive common table expression ‘%.*ls’.
467 16 GROUP BY, HAVING, or aggregate functions are not allowed in the recursive part of a recursive common table expression ‘<CTE Name>’.
468 16 Cannot resolve the collation conflict between «%.*ls» and «%.*ls» in the %ls operation.
469 16 An explicit column list must be specified for target table ‘%.*ls’ when table hint KEEPIDENTITY is used and the table contains an identity column.
470 16 The synonym «<Synonym Name>» referenced synonym «<Synonym Name>». Synonym chaining is not allowed.
471 16 Only one of the three options, SINGLE_BLOB, SINGLE_CLOB or SINGLE_NCLOB, can be specified.
472 16 Either a format file or one of the three options SINGLE_BLOB, SINGLE_CLOB, or SINGLE_NCLOB must be specified.
473 16 The incorrect value «%.*ls» is supplied in the PIVOT operator.
474 16 Unable to load the computed column definitions for table «%.*ls».
475 16 Invalid SAMPLE clause. Only table names in the FROM clause of SELECT, UPDATE, and DELETE queries may be sampled.
476 16 Invalid PERCENT tablesample size «<sample_number>» for table «<Table Name>». The PERCENT tablesample size must be between 0 and 100.
477 16 Invalid ROWS value or REPEATABLE seed in the TABLESAMPLE clause for table «<Table Name>». The value or seed must be an integer.
478 16 The TABLESAMPLE clause cannot be used in a view definition or inline table function definition.
479 16 Invalid ROWS value or REPEATABLE seed «%I64d» in the TABLESAMPLE clause for table «%.*ls». The value or seed must be greater than 0.
480 16 The TABLESAMPLE clause cannot be used with the table function «%.*ls».
481 16 The TABLESAMPLE clause cannot be used with the linked server table «%.*ls».
482 16 Non-constant or invalid expression is in the TABLESAMPLE or the REPEATABLE clause.
483 16 The OUTPUT clause cannot be used in an INSERT…EXEC statement.
484 16 Cannot declare more than %d local variables.
485 16 Views and inline functions cannot return xml columns that are typed with a schema collection registered in a database other than current. Column «%.*ls» is typed with the schema collection «%.*ls», which is registered in database «%.*ls».
486 16 %.*ls does not allow specifying a schema name as a prefix to the assembly name.
487 16 An invalid option was specified for the statement «%.*ls».
488 16 %s columns must be comparable. The type of column «%.*ls» is «%s», which is not comparable.
489 16 The OUTPUT clause cannot be specified because the target view «%.*ls» is a partitioned view.
490 16 The resync functionality is temporarily disabled.
491 16 A correlation name must be specified for the bulk rowset in the from clause.
492 16 Duplicate column names are not allowed in result sets obtained through OPENQUERY and OPENROWSET. The column name «%.*ls» is a duplicate.
493 16 The column ‘%.*ls’ that was returned from the nodes() method cannot be used directly. It can only be used with one of the four XML data type methods, exist(), nodes(), query(), and value(), or in IS NULL and IS NOT NULL checks.
494 16 The TABLESAMPLE clause can only be used with local tables.
495 16 The return table column «%.*ls» is not the same type as the type it was created with. Drop and recreate the module using a two-part name for the type, or use sp_refreshsqlmodule to refresh its parameters metadata.
496 16 The parameter «%.*ls» is not the same type as the type it was created with. Drop and recreate the module using a two-part name for the type, or use sp_refreshsqlmodule to refresh its parameters metadata.
497 16 Variables are not allowed in the TABLESAMPLE or REPEATABLE clauses.
498 16 Invalid value in the TABLESAMPLE or the REPEATABLE clause.
499 16 Invalid parameter for the getchecksum function.
500 16 Trying to pass a table-valued parameter with %d column(s) where the corresponding user-defined table type requires %d column(s).

Понравилась статья? Поделить с друзьями:
  • Mysql как изменить not null на null
  • Ms sql server error 9003
  • Mysql storage error 28 from storage engine
  • Ms sql server error 5030
  • Ms sql server error 3041 severity 16 state 1