question

Jackson1990-7147 avatar image
0 Votes"
Jackson1990-7147 asked TomCooper-6989 answered

Issue in SQL

Hi,
I want to get position of "(" within the string, and do not know what @p0 is 0.

Declare @str as varchar;
declare @p0 decimal(12,0)
select @str='MNO ()';
set @p0 =CHARINDEX('(',@str);
select @p0
--select substring(@str,1,@p0-1) as res
go


sql-server-generalsql-server-transact-sql
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

TomCooper-6989 avatar image
0 Votes"
TomCooper-6989 answered

When you declare a varchar (or any other datatype that can have a length like char, nvarchar, binary, etc), you want to always specify a length. If you don't, you will get a default length. In the case you have the default length of @str is 1. So the value put into @str is just the first character or 'M'. So @str does not have a '(' in it, so the result of the CHARINDEX is 0.

Tom

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered Viorel-1 edited

Try this declaration:

declare @str as varchar(max)


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.