Dynamic query SQL where condition - sql

I want to attach numeric value in dynamic query but I am an getting error:
Conversion failed when converting the varchar value ' + #psRegionCode + ' to data type smallint
My query is:
SET #psRegionCode = UPPER(LTRIM(RTRIM(#psRegionCode)))
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr + ' ' + 'AND reg.region_cd = ''' + #psRegionCode + ''''
END
Things which I tried:
SET #psRegionCode = UPPER(LTRIM(RTRIM(#psRegionCode)))
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr + ' ' +
'AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10) ''
END
Can somone please help me with this?

IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr +
' AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10))
you need to make sure you have correct number of apostrophes
if #psRegionCode is number, why you ltrim it? if it is a string why you cast it?

Well, by your syntax I'm guessing SQL-Server? Any way I think your second query should work, you are just missing a parenthesis :
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr +
' AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10))
END
You can't concat a number into a string without the conversion.

Related

Select more values on clause IF in the stored procedure

I have a problem of syntax in my stored procedure when a select more values in my IF, on code snippet 37 OR 35.
IF 37 OR 35 NOT IN (SELECT CodPerfilSistema
FROM [BRSAODB09].[ADMIN].[dbo].[PERFIL_USUARIO]
WHERE CodUsuario = #pCodUsuario)
BEGIN
SET #CondicaoEmpresa = ' AND [Lote].CodEmpresa = ' + CONVERT(varchar(10), #pCodEmpresa);
SET #CondicaoProjeto = ' AND [AUD_Projeto].CodProjeto = ' + CONVERT(varchar(10), #pCodProjeto);
END
I tried the code above.
And below is how the code is running
IF 37 NOT IN (SELECT CodPerfilSistema
FROM [BRSAODB09].[ADMIN].[dbo].[PERFIL_USUARIO]
WHERE CodUsuario = #pCodUsuario)
BEGIN
SET #CondicaoEmpresa = ' AND [Lote].CodEmpresa = ' + CONVERT(varchar(10), #pCodEmpresa);
SET #CondicaoProjeto = ' AND [AUD_Projeto].CodProjeto = ' + CONVERT(varchar(10), #pCodProjeto);
END
I need the permission for Id 37 and 35.
try the below
IF not exists (SELECT * FROM [BRSAODB09].[ADMIN].[dbo].[PERFIL_USUARIO] where CodUsuario = #pCodUsuario
and CodPerfilSistema in (37,35))
BEGIN
SET #CondicaoEmpresa = ' AND [Lote].CodEmpresa = ' + CONVERT(varchar(10), #pCodEmpresa);
SET #CondicaoProjeto = ' AND [AUD_Projeto].CodProjeto = ' + CONVERT(varchar(10), #pCodProjeto);
END
Thanks guys for the help, I found a way to solve the problem I had.
It stayed like this:
IF NOT EXISTS(
SELECT 1
FROM [BRSAODB09].[ADMIN].[dbo].[PERFIL_USUARIO]
WHERE CodUsuario = #pCodUsuario
AND CodPerfilSistema IN(37,35)
)
BEGIN
SET #CondicaoEmpresa = ' AND [Lote].CodEmpresa = ' + CONVERT(varchar(10),
#pCodEmpresa);
SET #CondicaoProjeto = ' AND [AUD_Projeto].CodProjeto = ' + CONVERT(varchar(10),
#pCodProjeto);
END

How to update table with while loop in Stored Procedure?

I want to update my dynamic table in while loop.
Here is my code:
While (#j<=#tmp_getRowCount)
Begin
Set #firstcolumn = (Select SplitFirst_tblAR from #result_AR Where rownumber = #j) //String//
Set #secondcolumn = (Select EMail_tblAR from #result_AR Where rownumber = #j) //String//
Set #thirdcolumn = (Select SplitFirst_tblKul from #result_AR Where rownumber = #j) //String//
Set #fourthcolumn = (Select EMail_tblKul from #result_AR Where rownumber = #j) //String//
insert into #test Values(#tmp_ID, #firstcolumn,#secondcolumn,#thirdcolumn,#fourthcolumn)
if ((#firstcolumn = #thirdcolumn) AND (#secondcolumn != #fourthcolumn) AND (#firstcolumn != ''))
begin
Set #q_updateTable = 'Update '+ quotename(#tablename) +' Set '+#columnname+' = ''' + #fourthcolumn + ''' Where ID = ' + #tmp_ID + ''
Exec sp_executesql #q_updateTable
end
SET #j = #j+1
End
My result_AR table:
I know the error is in here:
Where ID = ' + #tmp_ID + ''
When I change this Where clause as,
Where '+#columnname+' = ''' + #secondcolumn + ''' '
code works correctly.
Why can't I set as ID my where clause? I am getting ID value as integer.
The error is 'Query completed with errors'.
Thanks in advance.
you can not set Id in where clause because the id is integer value and you are concatenating it with string (varchar).
So first you have to convert it in (String)varchar and the you can use it where clause.
Like :
Set #q_updateTable = 'Update '+ quotename(#tablename) +' Set '+#columnname+' = ''' + #fourthcolumn + ''' Where ID = ' + convert(varchar,#tmp_ID) + ''
Exec sp_executesql #q_updateTable
you have to use "convert(varchar,#tmp_ID)" insted of "#tmp_ID"

SQL error: conversion failed when converting nvarchar value

I am attempting to write a fairly simple stored procedure but getting an error when I print #sql
set #where = ' where deliverydate between '''+ #FromDate + ''' and ''' + #ThruDate + ''''
set #where = #where + ' and custlocation = '+ #custlocationID + ''''
The error reads:
Conversion failed when converting the nvarchar value ' where deliverydate between '8/1/2013' and '8/20/2014' and custlocationID = ' to data type int.
#custlocationID is declared as int.
Can someone help with the apostrophes?
It's not the apostrophes that causes the error message. You are trying to add a string and an integer, and that will implicily convert the string to an integer.
Cast the integer to a string before you concatenate them:
set #where = #where + ' and custlocation = ' + cast(#custlocationID as varchar)

Dynamic WHERE clause in SQL Server 2008 R2

I have a table which I'm querying using a dynamic conditional WHERE clause. I'm looking a best approach to get simple WHERE condition when all columns are null or when some columns has some value.
I tried something like this:
SET #CONDITIONS = CASE
WHEN #VEHICLE_TYPE_NAME IS NULL
THEN ' ISNULL(A.VEHICLE_TYPE_NAME,'''') = ISNULL(A.VEHICLE_TYPE_NAME,'''') '
ELSE ' A.VEHICLE_TYPE_NAME = ''' + #VEHICLE_TYPE_NAME + ''''
END + ' ' + CASE
WHEN CAST(#PRODUCT_ID AS VARCHAR(MAX)) IS NULL
THEN ' AND ISNULL(A.PRODUCT_ID, ''-1'') = ISNULL(A.PRODUCT_ID, ''-1'') '
ELSE ' AND A.PRODUCT_ID = ''' + CAST(#PRODUCT_ID AS VARCHAR(MAX)) + ''''
END + ' ' + CASE
WHEN CAST(#CAPABILITY_ID AS VARCHAR(MAX)) IS NULL
THEN ' AND ISNULL(A.CAPABILITY_ID,''-1'') = ISNULL(A.CAPABILITY_ID,''-1'') '
ELSE ' AND A.CAPABILITY_ID = ''' + CAST(#CAPABILITY_ID AS VARCHAR(MAX)) + ''''
END + ' ' + CASE
WHEN #SPONSOR_FIRM_ID IS NULL
THEN ' AND ISNULL(A.SPONSOR_FIRM_ID,'''') = ISNULL(A.SPONSOR_FIRM_ID,'''') '
ELSE ' AND A.SPONSOR_FIRM_ID = ''' + #SPONSOR_FIRM_ID + ''''
END + ' ' + CASE
WHEN #CLIENT_FIRM_ID IS NULL
THEN ' AND ISNULL(A.CLIENT_FIRM_ID,'''') = ISNULL(A.CLIENT_FIRM_ID,'''') '
ELSE ' AND A.CLIENT_FIRM_ID = ''' + #CLIENT_FIRM_ID + ''''
END + ' ' + CASE
WHEN CAST(#DIST_PLATFORM_ID AS VARCHAR(MAX)) IS NULL
THEN ' AND ISNULL(A.DIST_PLATFORM_ID,''-1'') = ISNULL(A.DIST_PLATFORM_ID,''-1'') '
ELSE ' AND A.DIST_PLATFORM_ID = ''' + CAST(#DIST_PLATFORM_ID AS VARCHAR(MAX)) + ''''
END + ' ' + CASE
WHEN #RR_INTERNAL_NUMBER IS NULL
THEN 'AND ISNULL(A.RR_INTERNAL_NUMBER,'''') = ISNULL(A.RR_INTERNAL_NUMBER,'''') '
ELSE ' AND A.RR_INTERNAL_NUMBER = ''' + #RR_INTERNAL_NUMBER + ''''
END
You don't need the part where your parameter is null. You can simply build up a dynamic SQL for each part
IF #PRODUCT_ID IS NOT NULL
#CONDITIONS = #CONDITIONS + ' AND A.PRODUCT_ID = ''' + CAST(#PRODUCT_ID AS VARCHAR(MAX)) + ''''
Why do you need dynamic SQL?
WHERE (#VEHICLE_TYPE_NAME IS NULL OR A.VEHICLE_TYPE_NAME = #VEHICLE_TYPE_NAME)
AND (#PRODUCT_ID IS NULL OR A.PRODUCT_ID = #PRODUCT_ID)
...

Conversion failed when converting the nvarchar value to data type int

Do you know what could be wrong here?
All variables are nvarchar.
The error occurs when #FunctionValue contains an INT in string format.
IF #TargetType = 'INT'
BEGIN
SELECT #SQLSTR = 'UPDATE ' + #TargetTable +
' SET ' + #TargetColumn + ' = ' + COALESCE(CAST(#FunctionValue AS INT), CAST(#Value AS INT)) +
' '
END
The problem is the ambiguity of the + operator. When any argument is numeric, then it assumes you are doing numeric addition, rather than string concatenation.
If your original data is characters, then you can fix it by removing the cast entirely:
IF #TargetType = 'INT'
BEGIN
SELECT #SQLSTR = 'UPDATE ' + #TargetTable +
' SET ' + #TargetColumn + ' = ' + COALESCE(#FunctionValue, #Value) +
' '
END;
If your original data is numeric, then you need to explicitly convert them to characters:
IF #TargetType = 'INT'
BEGIN
SELECT #SQLSTR = 'UPDATE ' + #TargetTable +
' SET ' + #TargetColumn + ' = ' + cast(cast(COALESCE(#FunctionValue, #Value) as int) as varchar(255)) +
' '
END;
I also moved the "cast to int" outside the coalesce().
You are converting a 'varchar' and an 'int' without explicitly converting the types. When this happens, the data-type with the highest precedence wins. In this case, Int has a higher precedence than a varchar, therefore the whole statement becomes an Int. And converting an int to a varchar inexplicitly is not allowed.
Try wrapping a 'CAST ... as VARCHAR' around your Int values:
CAST(COALESCE(CAST(#FunctionValue AS INT), CAST(#Value AS INT)) AS NVARCHAR(255))
For a list of data-type precedences, see http://technet.microsoft.com/en-us/library/ms190309(v=sql.105).aspx
Hope this helps