SQL Help in procedure IN statement - sql

I ve follow procedure im SQL Server:
alter procedure sp_selectfFriends_by_cities
(
#txt_id_usuarios varchar(300)
)
as
begin
declare #sql varchar(300)
set #sql = 'select
a.int_id_usuario,
a.int_id_cidade,
b.txt_nome_cidade,
b.txt_nome_estado
from
tb_cidades_visitadas a
left join
tb_cidades
b on b.int_id_cidade = a.int_id_cidade
where int_id_usuario in (' + #txt_id_usuarios + ')'
execute(#sql)
end
Where #txt_id_usuarios is a list of users separated by commas,and the field int_id_usuario is type of BIGINT.
ie:
'6663225047,1122675730,1591119304,1664930592,1685923789,100000235882380,100000292471037,100000466411115'
When i try to execute it passing that string as parameter,it returns me follow error:
Incorrect syntax near '1685923789'.
But there is NO incorrect syntax.
Stranger if I remove some IDs it works.
I.E:
'6663225047,1122675730,1591119304,1664930592'
Works fine!
Any ideias?

Yes
declare #sql varchar(300)
This will limit your string to 300 chars. You need to make it longer

Related

Is it possible in a Sybase SQL query to substitute a string variable for the where clause?

I have two stored procedures that have different input signatures, but are otherwise identical and would like to consolidate them. I tried to simulate "overloading" the signature and then just testing which input variable is null to appropriately set the final where clause. I haven't figured out how to de-reference the string literal.
Procedures:
CREATE PROCEDURE get_providers (#p_id bigint)
SELECT
...
WHERE p.p_id = #p_id
CREATE PROCEDURE get_providers (#ssn varchar(9))
SELECT
...
WHERE p.ssn = #ssn
Trying to add this logic to set a dynamic WHERE clause:
CREATE PROCEDURE get_providers (#ssn varchar(9), #p_id bigint)
DECLARE #clause varchar(100);
SELECT clause = 'p.p_id = #provider_id';
IF #ssn is null
select clause = 'p.ssn = #ssn';
SELECT
...
WHERE #clause
Output:
ERROR: SQL Anywhere Error -131: Syntax error near '(end of line)'
on line 50 Error Code: 102
(note: line 50 is "WHERE #clause")
You can construct a complete query string and execute it Here is an example
declare #sql nvarchar(max);
select #sql = '
select . . .
from . ..
#whereclause';
select #sql = replace(#sql, '#whereclause', coalesce('where ' + #clause, ''));
exec(#sql);
You can't have just one part of the query be a string.
You're mixing up Watcom SQL and T-SQL. Both are supported by SA but you cannot mix them.
The following both work:
-- Watcom
begin
declare #c varchar(25);
set #c = "select ##version";
execute immediate #c;
end;
-- T-SQL
declare #c varchar(25)
set #c = "select ##version"
execute(#c)

sql how to write this as a script

I have the following sql query
Select * from Name
where surname in ('test1', 'test2')
which works
But I wanted to do the following
DECLARE #Surname as VARCHAR(100)
set #Surname = 'test1' + ',' + 'test2'
Select * from Name
where surname in #Surname
this is the actual query used
DECLARE #COESNo as VARCHAR(100)
set #COESNo = '121108883' + ',' + '121108890'
declare #sql varchar(max)
set #sql = 'select [LEI_ACCEPT] , [PREFERED_LEI] , [INSPECTION_COMPANY], [INSP_ACCEPT] from [CERTIFICATE_DETAILS] where [Certificate_no] in ('
set #sql = #sql + #COESNo + ')'
exec #sql
get the error
The name 'select [LEI_ACCEPT] , [PREFERED_LEI] , [INSPECTION_COMPANY], [INSP_ACCEPT] from [CERTIFICATE_DETAILS] where [Certificate_no] in (121108883,121108890)' is not a valid identifier.
doesn't seem to work
any ideas
There are two popular solutions.
First one is to build string with query and use sp_executesql to run it.
Second one is to write (or find) function (something like SplitText2Table()) which converts comma separated string to table and write query which use this function -- something like:
select *
from name
where surname in (select item from SplitText2Table(#surnames))
This is not a solution for the exact problem in the question. But maybe (?) you could instead use this workaround:
declare #SurName1 nvarchar(20)
declare #SurName2 nvarchar(20)
set #SurName1='test1'
set #SurName2='test2'
select * from [Name] where [surname] in (#SurName1, #SurName2)
you will need to create your statement and execute - like
declare #sql varchar(max)
set #sql = 'Select * from [Name] where surname in ('
set #sql = #sql + #surname + ')'
After creating the statement just say
exec #sql
You can also check the formed query is correct or not using print
print #sql
Please use print before execution of the command (this will help you in correcting the query is there is any error.).
EDIT:
As per the comment - Since Name is a keyword for SQL - we will need to use square bracket against it. I have modified the statement in my answer.
Edit 2: Based on further comments -
Firstly I would like to know the datatype of Certificate_no column in your database.
If it is a varchar field you will need to have single quotes around each value.
The name SELECT [LEI_ACCEPT] , [PREFERED_LEI] , [INSPECTION_COMPANY], [INSP_ACCEPT] FROM[CERTIFICATE_DETAILS] WHERE [Certificate_no] IN ('121108883','121108890')
You will need to create -
DECLARE #COESNo as VARCHAR(100)
set #COESNo = '''121108883''' + ',' + '''121108890'''
Since Certificate number is varchar the string build will need a single quote in formed query which will appear with three single quotes.
I have created Working DEMO for you on SQL FIDDLE - CLICK HERE

Conversion failed when converting the nvarchar value ... to data type int

I created the procedure listed below:
CREATE procedure getdata
(
#ID int,
#frm varchar(250),
#to varchar(250)
)
AS
BEGIN
DECLARE #SQL nvarchar(500)
set #SQL = 'select'
set #SQL = #SQL + ' EmpName, Address, Salary from Emp_Tb where 1=1 '
IF (#ID <> '' and #ID is not null)
Begin
SET #sql=#sql+' AND Emp_Id_Pk=' +#ID
End
END
print #sql
--execute (#sql)
I try to execute it using:
**execute getdata 3,'','';**
But I'm getting the following error:
Conversion failed when converting the nvarchar value 'select EmpName,
Address, Salary from Emp_Tb where 1=1 AND Emp_Id_Pk=' to data type int
Please help.
You are trying to concatenate a string and an integer.
You need to cast #ID as a string.
try:
SET #sql=#sql+' AND Emp_Id_Pk=' + CAST(#ID AS NVARCHAR(10))
Try Using
CONVERT(nvarchar(10),#ID)
This is similar to cast but is less expensive(in terms of time consumed)
I was using a KEY word for one of my columns and I solved it with brackets []
I use the latest version of SSMS or sql server management studio. I have a SQL script (in query editor) which has about 100 lines of code. This is error I got in the query:
Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the nvarchar value 'abcd' to data type int.
Solution - I had seen this kind of error before when I forgot to enclose a number (in varchar column) in single quotes.
As an aside, the error message is misleading. The actual error on line number 70 in the query editor and not line 2 as the error says!
don't use string concatenation to produce sql, you can use sp_executesql system stored prcedure to execute sql statement with parameters
create procedure getdata #ID int, #frm varchar(250), #to varchar(250) as
begin
declare #sql nvarchar(max), #paramDefs nvarchar(max);
set nocount on;
set #sql = N'select EmpName, Address, Salary from Emp_Tb where #id is null or Emp_Id_Pk = #id';
set #paramDefs = N'#id int';
execute sp_executesql #sql, #paramDefs, #id = #ID;
end
see sp_executesql
I got this error when I used a where clause which looked at a nvarchar field but didn't use single quotes.
My invalid SQL query looked like this:
SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = 13028533)
This didn't work since the Number column had the data type nvarchar. It wasn't an int as I first thought.
I changed it to:
SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = '13028533')
And it worked.
You got this Error because you tried to convert column DataType from String to int which is
leagal if and only if
you dont have row in that table with string content inside that column
so just make sure your previously inserted Rows is compatible with the new changes
I have faced to the same problem, i deleted the constraint for the column in question and it worked for me. You can check the folder Constraints.
Capture :
You must use CONCAT and not the +
SET #sql = CONCAT(#sql,' AND Emp_Id_Pk=' ,#ID )

How to set a variable to the result of a sql query with a variable as a table name in SQL 2005

I'm currently having trouble writing a stored procedure and setting the value of a variable of type int to the results of a select statement with a variable as the tablename. I've looked at old threads and tried multiple methods, but no luck. If I'm not getting an error regarding the tablename, I end up getting an error with a variable conversion issue. I've been working on this for too long and any help would be appreciated. Below is a portion of my code. Thanks
DECLARE #BATCHNUMBER VARCHAR --value set in earlier code
DECLARE #ETABLE VARCHAR(50); --the table name
DECLARE #FIRSTDOCID INT;
SET #ETABLE = 'tablename_' + #BATCHNUMBER; --CREATE FIRST TABLE NAME
SELECT #FIRSTDOCID = MIN(D0CID) FROM #ETABLE
The error I get is: Must declare the table variable "#ETABLE"
You are trying to select from a VARCHAR, not a table. The only way to make this work is by using Dynamic SQL.
DECLARE #SQL NVARCHAR(250);
SET #SQL = 'SELECT #OUTPUT = MIN(D0CID) FROM ' + QuoteName(#ETABLE);
EXEC sp_executeSql #SQL, N'#output INT OUTPUT', #FIRSTDOCID OUTPUT;
SELECT #FIRSTDOCID;
However, I would not suggest using Dynamic SQL as this often leads to SQL injection.
You'll probably have to do something like use exec if you're dynamically building the query:
SET #QUERY = "SELECT" + ...etc.
exec(#QUERY)
Since ETABLE is a varchar, and not, as expected, a 'table variable'.

Stored procedure causing syntax error

I have written this stored procedure :
CREATE PROCEDURE [dbo].[spGetCuisines]
#RestaurantID INT ,
#CuisineID NVARCHAR(200)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX)
SET #sql = 'SELECT CuisineID, CuisineName
FROM dbo.Cuisine1
WHERE CuisineID IN (
SELECT dbo.Dishes1.CuisineID
FROM dbo.Dishes1
WHERE DishID IN ( SELECT DishID
FROM dbo.RestaurantDish
WHERE RestaurantID = '
+ CAST(#RestaurantID AS NVARCHAR(MAX)) + ' ) )'
IF #CuisineID <> ''
BEGIN
SET #sql += 'AND Cuisine1.CuisineID IN('
+ CAST(#CuisineID AS NVARCHAR(MAX)) +')'
END
EXECUTE sp_executesql #sql;
END
I am using 3 tables with their columns listed below:
Dishes1
DishID
DishName
CuisineID
Price
Cuisine1
CuisineID
CuisineName
Type
DateCreated
DateModified
DateDeleted
RestaurantDish
RestaurantDishID
RestaurantID
DishID
but my stored procedure gives me syntax error on this line:
SET #sql += 'AND Cuisine1.CuisineID IN('+ CAST(#CuisineID AS NVARCHAR(MAX)) +')'
it says:
incorrect syntax near "+"
Can somebody guide me? Does the SQL Server version have something to do with this?
The syntax you are using is only valid on SQL Server 2008 and above. On SQL Server 2005, you'll have to change:
SET #sql += ...
To:
SET #sql = #sql + ...
There's absolutely no need to use dynamic SQL here - so don't ! Also: prefer JOIN over subqueries - joins are typically faster, and quite frankly - code is much easier to read!
Just use:
CREATE PROCEDURE [dbo].[spGetCuisines]
#RestaurantID INT ,
#CuisineID NVARCHAR(200)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX)
SELECT
c.CuisineID, c.CuisineName
FROM
dbo.Cuisine1 c
INNER JOIN
dbo.Dishes1 d ON d.CuisineID = c.CuisineID
INNER JOIN
dbo.Restaurant1 r ON r.DishID = d.DishID
WHERE
r.RestaurantID = #RestaurantID
AND (#CuisineID = '' OR c.CuisineID = #CuisineID)
END
And Aaron Bertrand is absolutely right, of course - this only works if you pass in a single CuisineID as string.
If your #CuisineID parameter contains multiple values then you need something like this instead:
WHERE
r.RestaurantID = #RestaurantID
AND (#CuisineID = '' OR c.CuisineID IN dbo.Split(#CuisineID))
Using a function Split you can split up a comma-separated list of ID's into a table variable and use the IN operator to match to a list of possible values.
are you perhaps passing in a comma delimited string??
If so, there is a better way to handle this, see here:
http://codebetter.com/raymondlewallen/2005/10/26/quick-t-sql-to-parse-a-delimited-string/