In my some of the columns have NULL value. So I can't achive other informations(my other columns) get NULL value. So I use Isnull. But I logged where I put Isnull() In my following code.

My Code is

SELECT TOP(10) 'INSERT INTO jobs(Budget) VALUES('+

    CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), 0, PATINDEX('%laks%', r.Budget))*100000

        + SUBSTRING(CAST(r.Budget AS VARCHAR(50)), PATINDEX('%laks%', r.Budget) + 4, 
        patindex('%Thousands%', r.Budget) - PATINDEX('%laks%', r.Budget) - 4)* 1000 AS VARCHAR(50))+')'

FROM requirementsdetailsfororganization r

In the above code, I calculate Salary in lakhs and Thousands. wherever i put Isnull(), It shows error.

Suggest me come out of this issue..

有帮助吗?

解决方案

Now this is what I think is happening

You may have used PATINDEX('%laks%', ISNULL(r.Budget,''))

Now PATINDEX() returns zero if pattern is not found. When you search pattern '%laks%' inside an empty string returned by ISNULL() , value zero is returned which causes error in SUBSTRING() function , something like index out of range

One of the solution is to filter out rows having null value or empty in Budget column. So you can add LEN() function and check whether it is not equal to zero . See the WHERE condition added in query below.

SELECT TOP(10) 'INSERT INTO jobs(Budget) VALUES('+

    CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), 0, PATINDEX('%laks%', r.Budget))*100000

        + SUBSTRING(CAST(r.Budget AS VARCHAR(50)), PATINDEX('%laks%', r.Budget) + 4, 
        patindex('%Thousands%', r.Budget) - PATINDEX('%laks%', r.Budget) - 4)* 1000 AS VARCHAR(50))+')'

FROM requirementsdetailsfororganization r
where len(r.Budget)<>0


For values having NULL in Budget column you can insert some default value like Zero

其他提示

To turn a null value to something that you can use in your string, you use it like this:

... + isnull( expression, 'null') + ...

If the value of expression is null, you get the string null instead to use in the query.

Also, to do multiplication with the values in your query, you first need to cast them to numbers.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top