TSQL RaiseError incorrect syntax, following MSDN's guidelines - sql

MSDN states the following syntax:
RAISERROR ( { msg_id | msg_str | #local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]
The msg_str expects a string up to 2047 characters but truncates longer strings. It also has the possibility of substituting parameters, which truncates the message further than the number of characters provided by the values:
The error message can have a maximum of 2,047 characters. If the message contains 2,048 or more characters, only the first 2,044 are displayed and an ellipsis is added to indicate that the message has been truncated. Note that substitution parameters consume more characters than the output shows because of internal storage behavior. For example, the substitution parameter of %d with an assigned value of 2 actually produces one character in the message string but also internally takes up three additional characters of storage. This storage requirement decreases the number of available characters for message output.
When msg_str is specified, RAISERROR raises an error message with an error number of 50000.
The severity expects a number between 0 to 25, but corrects other numbers:
Severity levels from 0 through 18 can be specified by any user. Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions. For severity levels from 19 through 25, the WITH LOG option is required. Severity levels less than 0 are interpreted as 0. Severity levels greater than 25 are interpreted as 25.
The state expects values 0 to 255, but corrects subzero values:
[state] is an integer from 0 through 255. Negative values default to 1. Values larger than 255 should not be used.
The issue
I get the following errors when I run these queries:
RAISEERROR('Test', 20, 1);
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Test'.
DECLARE #err_message nvarchar(255);
SET #err_message = 'Test';
RAISEERROR(#err_message, 20, 1);
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'RAISEERROR'.
I can execute various other queries just fine. E.g.:
THROW 50001, 'Test', 1;
Msg 50001, Level 16, State 1, Line 1
Test
More info
SELECT ##VERSION produces this:
Microsoft SQL Server 2016 (RTM-GDR) (KB3194716) - 13.0.1722.0 (X64) Sep 26 2016 13:17:23 Copyright (c) Microsoft Corporation Express Edition (64-bit) on Windows 8.1 Pro 6.3 (Build 9600: )
And the MSDN syntax was for "SQL Server (starting with 2008)" and as of writing, the article was updated October 19, 2016, which is months after the release of the SQL Server version I'm running.
What's going on here?

The docs:
MSDN states the following syntax:
RAISERROR
Your command:
RAISEERROR('Test', 20, 1);
I am always making this mistake. The command is not "Raise Error", but rather "Rais Error". I don't know why, but we're stuck with it...

Related

Parsing txt file with substring

I inherited a SQL code from my previous co-worker. The script was working the last time I ran it but it returns an error when I tried it today. Surprisingly the code is working on my colleague's PC. I double-check the SQL server database and we are using the same collation, Latin1_General_CS_AS. I did many tests, changing windows system locale etc however none of them work, the error is this:
Msg 207, Level 16, State 1, Line 141
Invalid column name 'Value'.
Msg 207, Level 16, State 1, Line 141
Invalid column name 'Value'.
...
However, I couldn't get it! why it is working on one system and not on another! Does anybody has any idea or alternative solution for the substring part.
DROP TABLE IF EXISTS #VievingLive0
SELECT
ProdDay, -- date
HouseId, -- ID
CAST(SUBSTRING(RowText, 2, CHARINDEX('_', RowText, 2)-2) AS INT) AS ChannelId, -- Channel ID
CASE WHEN LEN(s.Value) = 14 THEN LEFT(s.Value, 2) ELSE STUFF(LEFT(s.Value, LEN(s.Value)-12), 3, 0, '_') END AS Individs, -- list of persons
(LEN(s.Value)-12)/2 AS CntIndiv, -- number of persons watching
DATEADD(SECOND, substring(s.Value,LEN(s.Value)-11,2)*3600+substring(s.Value,LEN(s.Value)-9,2)*60+substring(s.Value,LEN(s.Value)-7,2), CAST(ProdDay AS DATETIME)) AS ViewFrom, -- time from
DATEADD(SECOND, substring(s.Value,LEN(s.Value)-5 ,2)*3600+substring(s.Value,LEN(s.Value)-3,2)*60+substring(s.Value,LEN(s.Value)-1,2)+1, CAST(ProdDay AS DATETIME)) AS ViewTo -- time to
INTO #VievingLive0
FROM #All_TX4_files
CROSS APPLY STRING_SPLIT(SUBSTRING(RowText, PATINDEX('%_[A-Za-z][A-Za-z][A-Za-z0-9]%', SUBSTRING(RowText, 2, LEN(RowText)))+2, LEN(RowText)), '_') AS s -- extracting individual vieiwng statemenets from the row
WHERE LEFT(RowText, 1) = 'V' -- LIVE viewing rows
I am trying to parse this format txt:
H98500410_0
W1941.51
Pab_2467211514110343733611_W2898.81
V100_0_2_210_ab075700080859_ab081100081259_ab081700081959_ab082800083059_ab083400083559_ab110600110959_ab111300111459_ab113500115059_ab115300120259_ab120300120359_ab120400123059_ab123100123559_ab124800125359_ab173200173259_ab191200191359_ab191600191759

Cannot continue the execution because the session is in the kill state

I try to execute a update query in SQL Server 2016 (v13.0.5026.0) and get these error messages:
Msg 596, Level 21, State 1, Line 0
Cannot continue the execution because the session is in the kill state.
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
Checked for corrupted index or anything
DBCC CheckDB (DBNAME) WITH NO_INFOMSGS, ALL_ERRORMSGS
--Returns no error
As Microsoft suggested update with the below link:
https://support.microsoft.com/en-us/help/4163478/fix-access-violation-when-incremental-statistics-automatically-updated
I tried an update to Cummulative Update(CU6) and changed to 13.0.5292.0
It says CU1 update has to fix it but doesn't solve the issue.
The query is:
UPDATE tableName
SET fieldName1 = 'a long query with some html tags and all it has 3600 chars'
WHERE fieldName2 = 12345
It doesn't have any special characters that SQL can't handle.
Any help would be great.

SQL Error near the word 'go'

Why does SQL Server report that this statement isn't correct?
use DIGITECH
go
select *
from kunde as k
left join adresse as a on k.FK_AdID = a.AdID
where Name = 'Dirk'
go
SQL displays this error (in German):
Meldung 102, Ebene 15, Status 1, Zeile 14
Falsche Syntax in der Nähe von 'go'.
Meldung 102, Ebene 15, Status 1, Zeile 14
Falsche Syntax in der Nähe von 'go'.
Translated to english:
Msg 102 , Level 15 , State 1, Line 14
Incorrect syntax near 'go' .
Msg 102 , Level 15 , State 1, Line 14
Incorrect syntax near 'go' .
As other have pointed out, GO is the default batch delimiter for tools like Management Studio or sqlcmd. SQL Server does not understand GO, the tools use it to separate batches and send individual batches to SQL Server. You probably took an entire .sql file and executed in your app.
You can use a library like DbUtilSqlCmd which understands the sqlcmd delimiters (GO), and other sqlcmd specific syntax like :setvar, and execute your .sql file through it.
Can you specify the database in the query and avoid the go statements? For example:
select * from DIGITECH.dbo.kunde as k
left join DIGITECH.dbo.adresse as a
on k.FK_AdID = a.AdID
where Name = 'Dirk'

raiserror shows one message, but not another

I have this code:
DECLARE
#timestamp varchar(20),
#latestFeed INT,
#LargestKeyProcessed INT,
#NextBatchMax INT,
#RC INT;
SET #timestamp = CAST(CURRENT_TIMESTAMP as varchar(20));
SET #latestFeed = (SELECT MAX([feed_id]) FROM [dbo].[CAQH_RESP_ALL_TEST_MIRROR]);
SET #LargestKeyProcessed = (SELECT MIN([record_id]) - 1 FROM [dbo].[CAQH_RESP_ALL_TEST_MIRROR] WHERE [feed_id] = #latestFeed);
SET #NextBatchMax = 1;
SET #RC = (SELECT MAX([record_id]) FROM [dbo].[CAQH_RESP_ALL_TEST_MIRROR]);
raiserror(#timestamp, 0, 1) with nowait
raiserror(#LargestKeyProcessed, 0, 2) with nowait
WHILE (#NextBatchMax < #RC)
BEGIN
BEGIN TRY
--do some stuff
COMMIT TRANSACTION flagHandling
raiserror('Transaction Committed', 0, 3) with nowait
raiserror(#timestamp, 0, 4) with nowait
raiserror(#LargestKeyProcessed, 0, 5) with nowait
END TRY
BEGIN CATCH
--catch some stuff
END CATCH
END
It seems to run fine, but has a couple of things that seem odd to me. At the outset, it prints the date as I'd expect to see it, but then prints an actual error message with the raiserror I'm using. I'm using the exact same syntax, but one prints only the desired timestamp, while the next produces
Jul 23 2015 9:09AM
Msg 18054, Level 16, State 1, Line 16
Error 33218606, severity 0, state 2 was raised, but no message with that
error number was found in sys.messages. If error is larger than 50000,
make sure the user-defined message is added using sp_addmessage.
Then, after the transaction is committed, it correctly shows the following messages:
Transaction Committed
Jul 23 2015 9:11AM
But leaves out the last message which should show the value of #LargestKeyProcessed. This raiserror message is the same one as the raiserror message at the beginning of the script that produces the aforementioned odd behavior.
I just want to have the messages print to the messages window without looking like an error, and also want to have ALL the messages print. What am I doing wrong here?
You're giving an int to raiserror, which means you're using the msg_id functionality:
RAISERROR ( { msg_id | msg_str | #local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]
msg_id:
Is a user-defined error message number stored in the sys.messages
catalog view using sp_addmessage. Error numbers for user-defined error
messages should be greater than 50000. When msg_id is not specified,
RAISERROR raises an error message with an error number of 50000.
You should use varchar variables, and that can then contain the number which you want to send. See the documentation.

SQL facing error while running bcp

i am facing error wile running this in sql server 2000
bcp "select dmedocno ,dmename,dmeauthor,dmekeywords from document
where repositoryid=4 and dmedocno between 1 and 60000 order by
dmedocno" queryout c:\LR_Query29_cutover_19_August.csv -Swsapp0772 -T -c -t","
Error is:
Server: Msg 103, Level 15, State 7, Line 1
The identifier that starts with 'select dmedocno ,dmename,dmeauthor,dmekeywords from document where repositoryid=4 and dmedocno between 1 and 60000 order by dmed' is too long. Maximum length is 128.
Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near 'queryout'.
why your sql server treats the query as identifier? hm...
Check default QUOTED_IDENTIFIER option for the server, try to set it to OFF