Why has different output of function replace? - sql

declare #tachareName varchar(200)
,#a varchar
set #tachareName='fsfhk,fsif,'
if(CHARINDEX(',',#tachareName)!=0)
--print #tachareName
--select REPLACE(#tachareName,',',' ')--The output is:fsfhk fsif
set #a=REPLACE(#tachareName,',',' ')
--REPLACE(#tachareName,',',' ')
print #a --The output is:f
What's wrong,i want to judge if the string has ',' symbal and repalce it with ' '.
The envirioment is SQL Server 2008.

Because of your declaration of #a - you have not declared length of variable so it defaulted to 1. Thus returning only the first letter of result.
Declare #a as:
declare #a varchar(200)
Read more about char and varchar declaration on MSDN.

Related

Why do I have two different return values from the queries in T-SQL

Hello I wonder why I have 2 different return Values.
Here is the first query:
declare #currentcolumn_val varchar
declare #start integer
set #currentcolumn_val = 'state_val'
set #start =1
select #currentcolumn_val from z_skm where id = #start
the returned value is just "s"
Here is the second Query which gives the correct return value:
select state_val from z_skm where id = 1
This query gives me exactly what it should.
I hope you guys can help.
Cheers steven
Your first query is returning a constant. The second is returning the value of the column.
You are returning 's' instead of 'state_val' because of the declaration:
declare #currentcolumn_val varchar;
You have no length on varchar() and in this context, it defaults to a length of 1. Always use length with varchar() in SQL Server.
If you want the column to be dynamic, you need to use dynamic SQL:
declare #currentcolumn_val nvarchar(255);
declare #start integer;
declare #sql nvarchar(max) = 'select #currentcolumn_val from z_skm where id = #start';
set #sql = replace(#sql, '#currentcolumn_val', #currentcolumn_val);
exec sp_executesql #sql, N'#start int', #start = #start;
You can pass a parameter as an argument, but not a column or table name.
You have declared #currentcolumn_val simply as varchar, which defaults to a length of 1.
if you replace it with declare #currentcolumn_val varchar(10) you will see the whole value
First you haven't given the #currentcolumn_val parameter a size so it is equivalent to a VARCHAR(1). This means that this:
set #currentcolumn_val = 'state_val'
Is the essentially the same as:
set #currentcolumn_val = 's'
Then in your SELECT you are returning the value of that variable, not a column from the table.

using user variable in 'IN' clause of sql

declare #A varchar(5000)
declare #B varchar(5000)
select #A=value from drp.Parameter where parameteridname='IV01'
--result of this query ('DIM003966','DIM000736','DIM025297',
-- 'DIM025302','DIM027583')
select [InventLocationId],[WMSLocationId] from ItemKit.InventDim
where inventdimid in (#A)
i am not getting any result out of second query but if i run them individually and use result of 1st query in second i am getting it. is there any way around to run them together
That is because it evaluates #a as is (as text, not a list of values).
You should create a sql statement on the fly and execute it:
declare #sqlStatement nvarchar(4000)
#sqlStatement = 'select [InventLocationId],[WMSLocationId] from ItemKit.InventDim where inventdimid in (' + #A + ')'
execute sp_executesql #sqlStatement
But as said by others, don't use unless really necessary.
You should use this code:
select [InventLocationId],[WMSLocationId] from ItemKit.InventDim
where inventdimid in (select value from drp.Parameter where parameteridname='IV01')
As you have a single string value (holding all the values) you could either:
Parse sql on the fly
Note: I do not recommend this, as it can allow sql injection
(see #Patrick Hofman's answer for good example of this)
Use like
declare #A varchar(5000)
declare #B varchar(5000)
select #A=value from drp.Parameter where parameteridname='IV01'
--result of this query ('DIM003966','DIM000736','DIM025297',
-- 'DIM025302','DIM027583')
SELECT #A /* Here you will see the problem, as it is not multiple values,
it is a single string with a comma & quote (') delimited list */
SELECT
[InventLocationId], [WMSLocationId]
FROM
ItemKit.InventDim
WHERE
/* parse up the inventdimid to include the quote (') around it */
#A like '%''' + #inventdimid + '''%'

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 )

Extracting nvarchar value from XML in T-SQL: only one character returned

In my T-SQL procedure I'm trying to extract a string value from the XML node using the .value() method, like this:
declare #criteria xml;
set #criteria = N'<criterion id="DocName"><value>abcd</value></criterion>';
declare #val nvarchar;
set #val = #criteria.value('(criterion[#id="DocName"]/value)[1]', 'nvarchar');
select #val;
I expected to get 'abcd' as a result, but I surprisingly got just 'a'.
So, the value method returns only the 1st character of the string. Can anybody tell me, what am I doing wrong? Thanks a lot.
P.S. I'm using MS SQL Server 2012
Don't use nvarchar without size. From documentation:
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified with the
CAST function, the default length is 30.
If you don't know exact length, you always can use nvarchar(max):
declare #criteria xml;
set #criteria = N'<criterion id="DocName"><value>abcd</value></criterion>';
declare #val nvarchar(max);
set #val = #criteria.value('(criterion[#id="DocName"]/value)[1]', 'nvarchar(max)');
select #val;
sql fiddle demo

How to user prefix 'N' for unicode with nvarchar variable in SQL Server?

How to user prefix 'N' for unicode with nvarchar variable in SQL Server? For example:
Given this variable:
declare #Query1 nvarchar(max)
I can assign to it like this:
set #Query1 = N'لاحظات'
But what if I want to use N#Query1 somewhere?
You only need to use N'xyz' when you have literal text. Once the nvarchar data is in a variable or result set column of nvarchar data type you no longer need to use the N'...' notation, the system knows the data type at that point.
try it out:
DECLARE #A nvarchar(100)
,#B nvarchar(100)
SET #A = N'anything here!!'
SET #B=#A --would work the same if coming from a query result set as well
SELECT #B --will show special unicode characters
declare #nv1 nvarchar(50) = N'لاحظات', #nv2 nvarchar(50) = 'لاحظات', #v varchar(50) = N'لاحظات'
declare #nv3 nvarchar(50) = #nv1 + ' hallo', #nv4 nvarchar(50) = #nv1 + N' hallo'
select #nv1, #nv2, #nv3, #nv4, #v
It is used with string literals to indicate the text should be treated as unicode. e.g.
DECLARE #something NVARCHAR(100)
SET #something = N'sometext'
Declare #var nvarchar(255)
Set #var = N'Hello World'
print #var
create table #tmp( columnA nvarchar(255) not null)
insert into #tmp(columnA) Values (N'Test')
Select #var = columnA from #tmp
print #var
drop table #tmp
Thanks to marc_s for his answer, that solved my problem.
I highlight it here as an answer for those who can't find it.
"
if #Query1 IS a NVARCHAR variable, then it IS a NVARCHAR variable and you don't need to prefix it with another 'N' to make it NVARCHAR.... just use it
"