SELECT statement with IN and input variable in SQL server [duplicate] - sql

This question already has answers here:
T-SQL stored procedure that accepts multiple Id values
(5 answers)
Closed 2 years ago.
Having a table (Table1) with Columns -> Column1 int, Column2 int, Column3 varchar(128), Column4 char(11)
Need to create a stored procedure to get the details from Table1 based on the input parameter. Input parameter holds values with comma-separated. It has to be mapped with Column1
Create Procedure ProcedureName(#InputParams VARCHAR(MAX))
AS
BEGIN
SELECT Column2
,Column3
,Column4
FROM Table1
WHERE Column1 IN (#InputParams)
ORDER BY Column2
END
The below statement is throwing conversion error
"Conversion failed when converting the varchar value '123, 456, 789' to data type int."
EXEC ProcedureName #InputParams = '123, 456, 789'
Converting the SELECT statement to the dynamic query will work fine but will we able to fix the conversion issue in the static query. Please help me.

Well, you have a couple of options in this case :
Table-valued input parameter : For this, you'll have to create a UDT (user-defined table type) and use that as the parameter to your stored procedure.
Convert the comma-separated input string parameter into integers and then use them in the IN clause.
Not sure about your use-case, but generally, I would suggest going forward with the first option.

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.

Update of table not happening on datatype 'Text' [duplicate]

This question already has answers here:
WHERE clause on SQL Server "Text" data type
(7 answers)
Closed 5 years ago.
update SubCategoryMaster
set SubCategoryDescription='SHARPENERANDRULER'
where SubCategoryDescription='SharpenerAndRuler'
In this query, SubCategoryDescription's datatype is TEXT. When I execute this query, I get an error:
Msg 402, Level 16, State 1, Line 1
The data types text and varchar are incompatible in the equal to operator.
Please suggest
blog.sqlauthority.com has an answer for you. The following is the relevant part of the blog post, in case this link is dead:
Solution 1: Convert the data types to match with each other using CONVERT function.
Change the datatype of the MyText to nvarchar.
SELECT ID, MyText
FROM TestTable
WHERE CONVERT(NVARCHAR(MAX), MyText) = N'AnyText'
GO
Solution 2: Convert the data type of columns from NTEXT to NVARCHAR(MAX) (TEXT to VARCHAR(MAX)
ALTER TABLE TestTable
ALTER COLUMN MyText NVARCHAR(MAX)
GO
Now you can run the original query again and it will work fine.
Solution 3: Using LIKE command instead of Equal to command.
SELECT ID, MyText
FROM TestTable
WHERE MyText LIKE 'AnyText'
GO

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

How to column schema of arbitrary query in SQL server

I want to get just schema of arbitrary sql query in SQL server.
For example-
Create Table Tabl1(Ta1bID int ,col1 varchar(10))
Create Table Tabl2(Tab1ID int ,col2 varchar(20))
SQL Query -
SELECT col1, col2
FROM Tab1
INNER JOIN Tab2 ON Tab1ID = Tab2ID
Here result will have this schema-
Col1 varchar(10), Col2 varchar(20)
I want to know what will be schema of result.
PS : I have just read access on the server where I am executing this query.
Any way to do this?
The schema, you mean to say datatype right? For resulted datatype will you always know when you operate on table(s). In your case both column is varchar datatype, so it will give character datatype, that you may convert into any character datatype like varchar, nvarchar, char, ntext etc.
Basic thing is, table designing was/is done by, so that time we know why we define datatype, now when you execute query below , you always know what will come with datatype of each column.
SELECT col1, col2
FROM Tab1
INNER JOIN Tab2 ON Tab1ID = Tab2ID
This though will issue when you use dynamic query, where you run time add column as per your requirement and you then execute which may or may not give error, due to mismatch of wrong datatype.
like
declare #sqlstring nvarchar(max)
set #sqlstring = 'declare #t table (name varchar(50))
insert into #t values(''Minh''),(''Tinh''),(''Justin'')
Select * from #t where Name like ''%in%'''
EXEC sp_executesql #sqlstring
I had similar problem before, but I had to create tables (70+) of each query one by one.
If there is a pattern, write a tool to generate create table
statement.
If not and it's one time job, just create them manually.
If it's not one time job, you might be thinking, why would store temp
date in table instead of temp table.

SQL union between NULL and VARCHAR error

I have two views with identical columns. One of the columns on the first view is generated 'on the fly' and set as NULL and the same column on the other view has values stored as varchar. I have a stored proc that looks like this:
ALTER PROCEDURE [dbo].[mi_GetLearners]
(#centrename nvarchar(200))
AS
SELECT [centrename]
,[Name]
,[Username] --generated on the fly as NULL
FROM [DB1].[dbo].[vw_Learners]
WHERE [centrename] = #centrename
UNION
SELECT [centrename]
,[Name]
,[Username] --values stored as varchar
FROM [Linked_Server].[DB2].[dbo].[vw_Learners]
WHERE [centrename] = #centrename
DB1 is on SQL Server 2008 R2
DB2 is on SQL server 2005
When I run the stored proc I get the following error:
Msg 245, Level 16, State 1, Line 1 Conversion failed when converting
the varchar value 'someusername' to data type int.
Why is it trying to convert the value to int datatype as the other column is set as NULL? If I instead change the second column from NULL to ' ' the stored proc works fine... I'm really baffled as to why a union between a varchar column and NULL column generated in a select statement would throw such an error... any ideas?
EDIT: I'm looking for an explanation rather than a solution...
EDIT 2: Running the following code:
CREATE VIEW vw_myview
AS
SELECT NULL AS MyColumn
EXECUTE sp_help vw_myview
Returns:
Type Column_name
int MyColumn
The problem is that NULL is (to within some wiggle room) a member of every data type.
When any SELECT query is being run, the contents of each column must be of one type, and only one type. When there are a mixture of values in a column (including NULLs), the type can obviously be determined by examining the types of the non-NULL values, and appropriate conversions are performed, as necessary.
But, when all rows contain NULL for a particular column, and the NULL hasn't been cast to a particular type, then there's no type information to use. So, SQL Server, somewhat arbitrarily, decides that the type of this column is int.
create view V1
as
select 'abc' as Col1,null as Col2
go
create view V2
as
select 'abc' as Col1,CAST(null as varchar(100)) as Col2
V1 has columns of type varchar(3) and int.
V2 has columns of type varchar(3) and varchar(100).
I'd expect the type of the field to be determined by the first SELECT in the union. You may try changing the order of your two selects or change to CAST(NULL AS VARCHAR(...)).
I think you need to cast to the same datatype:
---
AS
SELECT [centrename]
,[Name]
,CAST(NULL AS VARCHAR(MAX)) AS [Username]
FROM [DB1].[dbo].[vw_Learners]
WHERE [centrename] = #centrename
UNION
---