STORED PROCEDURE CONVERT ERROR - sql

Have stored procedure where i want update data and want cast some varbinary to nvarchar
UPDATE [payterm].[dict_default_values]
SET [default_value] = CAST(#value AS NVARCHAR(MAX))
,[descr] = CAST(#descr AS NVARCHAR(MAX))
,[grp] = #grp
WHERE [code] = #code;
IF ##ROWCOUNT = 0
INSERT INTO [payterm].[dict_default_values]
([code], [default_value], [descr], [grp])
VALUES
(#code, #value, #descr, #grp);
When i put parametrs there were error : Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query

You also need to cast in the VALUES part of your INSERT statement.
Without knowing the data types of your variable/parameters/columns it's difficult to give a specific answer though.

Related

Why this simple stored procedure isn't working

Here is the deal, I am receiving an array from C# and I want to insert it into the following table with only 2 columns which are #idUser int and #idRegion int.
The stored procedure needs to receive the array and insert it into the table but somehow it isn't working, it tells me that it cannot convert #idRegion to an int. I tried to use CAST and CONVERT to convert it into int but it isn't working.
The Select From works ok, but not the insert.
Here is the stored procedure (#idUser needs to be the same for all inserted rows):
#idUser int,
#idRegion nvarchar(MAX)
AS
BEGIN
INSERT INTO [UsersRegion] (idUser,IdRegion)
VALUES (#idUser, #idRegion)
SELECT #idUser,cast(value as int) FROM STRING_SPLIT(#idRegion,',')
END
I get this error when running it:
Conversion failed when converting the nvarchar value '1,2,3,4' to data type int.
If you are sending multiple values in #idRegion then when you split them, you may have more than 1 things you need to insert. Therefore, do it like this:
INSERT INTO [UsersRegion] (idUser,IdRegion)
SELECT #idUser, value FROM STRING_SPLIT(#idRegion, ',')
If the target table's IdRegion column is of type int, you need to cast like this:
SELECT #idUser, cast(value as int) FROM STRING_SPLIT(#idRegion, ',')
Above code will insert the same #idUser for every record but a different value for IdRegion depending the splitted items. More on Insert into select from
Your INSERT statement seems to be working with IdRegion while everything else is lowercase id.
However, assuming this is how the actual table column is named and is not a typo...
Your problem is most likely the line that reads:
#idRegion nvarchar(MAX)
Which is declaring the #idRegion variable as a string, while you have stated in the question that it's meant to be an int.
This would explain the casting error.
If you cannot pass it into the procedure as an int from the C# code. Your only other option would be to try to parse it into an int as you have said.

Error converting varchar to bigint

I got the error where my data type is varchar, then I want to insert value/input in textboxt = 'smh85670s'.
It appear to be error. As far as I know varchar can accept characters and numbers, but why does it keep throwing this error?
If I insert value '123456' the table can accept that value.
Please guide me. What data type should I use?
Assuming that you are using Stored procedures (which have an insert query) or directly firing an insert query into DB, you must be sending all data as parameters like say #param1, #param2,...
Your insert query will be like
INSERT INTO Sometable ( Amount, textbox,... )
SELECT #param1, #param2 ,...
Just add a cast in this query to make it work
INSERT INTO Sometable ( Amount, textbox,... )
SELECT #param1, CAST(#param2 as varchar),...

Difficulty printing one particular query in MSSQL

I'm trying to construct a small query which will pull data from individual fields in a DB and print them in a human readable list format (it's what the operators are used to seeing). The code I have here is far from complete but It seems to me that it should work.
DECLARE #PSUCARD VARCHAR(20)
DECLARE #EQUIPMENT VARCHAR(50)
DECLARE #T1 VARCHAR
SET #PSUCARD = 'PSU-888'
SET #EQUIPMENT = '123_POUCH'
PRINT #PSUCARD + ':'
PRINT #EQUIPMENT
PRINT ''
IF (SELECT TEMPERATURE_MAIN FROM PSU WHERE PSU.PART_ID = #PSUCARD AND PSU.OPERATION_RESOURCE_ID = #EQUIPMENT)IS NOT NULL BEGIN
SET #T1 = (SELECT TEMPERATURE_MAIN FROM PSU WHERE PSU.PART_ID = #PSUCARD AND PSU.OPERATION_RESOURCE_ID = #EQUIPMENT)
PRINT 'Temperature: ' + #T1
--(SELECT TEMPERATURE_MAIN FROM PSU WHERE PSU.PART_ID = #PSUCARD AND PSU.OPERATION_RESOURCE_ID = #EQUIPMENT)
END
If I execute the code as is, #T1 returns a * rather than a value. If I remove comments from the line below I am reassured that there is indeed a value there.
I have other code very similar to this which works fine. Any ideas?
Also, I don't know if this helps in diagnosing the problem, but despite the temperature field in the DB being an INT, I get a conversion message if I try to treat #T1 an an INT.
This is because you declared #T1 as VARCHAR without a length. According to this:
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified when using
the CAST and CONVERT functions, the default length is 30.
You should always specify a length when declaring a VARCHAR variable:
DECLARE #T1 VARCHAR(50)
You need to give length for varchar datatype else it is going to take only one character
DECLARE #T1 VARCHAR(50)

Need help in parsing json string in SQL stored procedure and accessing its attribute's value

I want to parse json string coming from request, extract particular information from that string and then based on that information need to call relevant update statements.
In java service it would be bit tedious to do this task as need to send each parameter separately and call relevant update statements.
If I can do the same task in stored procedure then it would be efficient. is there any way I can parse this same json string in a SQL stored procedure and update corresponding fields of tables by value of related attributes ?
Sample json string is -
{"category1":{"field1":"value1","field2":"value2"}}
this I want to send as a parameter of stored procedure
and I want to call update statement to update fields of related table with value1 and value2.
How can I parse these values in stored procedure from json string that I pass as a parameter to it?
I know this would be better off as a comment but I currently don't have that many rep points..
With that said you could try comma-schema.
I noticed this article using it.. I think you could use it to do the same.
Basically create data like the above article then update as needed
Definitely you can use JSON in a Stored procedure. This is a best way to make your DB closer to REST APIs. Your Stored procedure can have input and output both as JSON. It is just that you have to put efforts in writing a good stored procedure. rather than exposing a random access to API/user for querying it directly
here is one of the example:
DECLARE #out VARCHAR(max) =''
EXEC csdm.your_sp
#input = <your_JSON_string>,
#output = #out OUTPUT
SELECT #out
Now to achieve this write your SP as
CREATE PROCEDURE dbo.your_sp
#input VARCHAR(max),
#output VARCHAR(max) OUTPUT
AS
PRINT 'PROC_START : dbo.your_sp'
-- Declare variables as needed
DECLARE #sp_output VARCHAR(max)
DECLARE #json_category VARCHAR(max)
DECLARE #json_category VARCHAR(max)
-- Validate JSON
IF(ISJSON(#input) = 0)
BEGIN
SET #sp_output = '{"status":"Error","errorTitle":"Invalid Input JSON","errorMessage":"JSON sent as input is Incorrect, please verify and fix"}'
END
ELSE
BEGIN
-- Process JSON if valid JSON provided
-- Option 1
INSERT INTO myTable
(Field1, Field2)
VALUES
(
SELECT [VALUE] FROM OPENJSON(#op, '$.category1') where [KEY] = 'field1',
SELECT [VALUE] FROM OPENJSON(#op, '$.category1') where [KEY] = 'field1'
)
SET #sp_output = '{"status":"Success", "message":"Record updated successfully"}'
-- Option 2 : Can have more validation for the data
SELECT #json_category = VALUE FROM OpenJson (#input, '$') WHERE [Key] = 'category1'
SELECT #json_field_value = VALUE FROM OpenJson (#json_category, '$') WHERE [Key] = 'field1'
IF(#json_category IS NOT NULL OR #json_category <> '') AND (#json_field_value IS NOT NULL OR #json_field_value <> '')
BEGIN
INSERT INTO myTable
(Field1, Field2)
VALUES
(
SELECT [VALUE] FROM OPENJSON(#op, '$.category1') where [KEY] = 'field1',
SELECT [VALUE] FROM OPENJSON(#op, '$.category1') where [KEY] = 'field1'
)
SET #sp_output = '{"status":"Success", "message":"Record updated successfully"}'
END
ELSE
BEGIN
SET #sp_output = '{"status":"Error","errorTitle":"Blank/Missing Input provided","errorMessage":"Critical / Mandatory data is missing in the input JSON"}'
END
END
-- Build Output or Error response
SET #output = #sp_output
PRINT 'PROC_END : dbo.your_sp'
RETURN
GO
This is just a sample to show how to use JSON, you can do a lot more in this additionally

Transact SQL, how can I take varchar type, convert to int, add one, convert back to string, then store?

ALTER PROCEDURE [dbo].[AmendInsertDuplicateFields] (#ReportID varchar(50))
AS
BEGIN
DECLARE #NewReportID VARCHAR(50)
SET #NewReportID = NEWID()
INSERT INTO [MVCOmar].[dbo].[PrideMVCCollisionBegin]
([ReportID], [LocalIncidentNum], [version], [MTOReferenceNo], [Submitted])
SELECT
#NewReportID, [LocalIncidentNum], [version], [MTOReferenceNo], [Submitted]
FROM
[MVCOmar].[dbo].[PrideMVCCollisionBegin]
WHERE
[ReportID] = #ReportID;
I would like to take the result that I get for version, convert it from string to int type, add one, convert back to string, and store it.
I acknowledge that version should be int and not string type. I also acknowledge that an even better method of accomplishing this would be to set properties to increment by one.
I can't do either of those option for the time being because my priorities are different right now, I am time limited, the code is very old, and written by numerous people which carried poor coding habits.
you don't need to convert it, run this, there will be an implicit conversion
SELECT '1' + 1
That returns 2
In your case you can just do [version] + 1
You can do this inline in your SELECT statement, using the CONVERT function:
INSERT INTO [MVCOmar].[dbo].[PrideMVCCollisionBegin] ([ReportID], [LocalIncidentNum], [version], [MTOReferenceNo], [Submitted])
SELECT #NewReportID, [LocalIncidentNum],
CONVERT(VARCHAR, (CONVERT(INT, [version]) + 1)),
[MTOReferenceNo], [Submitted]
FROM [MVCOmar].[dbo].[PrideMVCCollisionBegin]
WHERE [ReportID]=#ReportID;
SQL Server supports CAST or CONVERT
CAST(col1 as int)
CONVERT(int,col1)