1

Unknown error in Dynamic String Handling in a T-SQL Environment. PS: I am not going to do any conversions. Just want to create an Update statement and execute it later

Code:

DROP TABLE IF EXISTS #TEMP

Select 'CRDB_Reporting' tablename,'MagnitudePackage' updatecolumn,'String' updatecolumntype,'''XLFWH''' updatevalue,'NatureOfFundCode' primaryfilter,'String' primaryfiltertype,'''FWH''' primaryfiltervalue,NULL remainingfilter
INTO #TEMP

Select  
CASE 
WHEN remainingfilter IS NOT NULL THEN 
    'Update [dbo].[' + tablename +'] Set [' + updatecolumn +']  = ' + updatevalue + ' Where [' + primaryfilter +']  = ' + primaryfiltervalue + ' And ' + remainingfilter
WHEN remainingfilter IS NULL THEN   
    'Update [dbo].[' + tablename +'] Set [' + updatecolumn +']  = ' + updatevalue + ' Where [' + primaryfilter +']  = ' + primaryfiltervalue + ' And '
END
From #Temp

Expected Result

Update [dbo].[CRDB_Reporting] Set [MagnitudePackage] = 'XLFWH' Where [NatureOfFundCode] = 'FWH'

Error Msg:

Msg 245, Level 16, State 1, Line 34 Conversion failed when converting the varchar value 'Update [dbo].[CRDB_Reporting] Set [MagnitudePackage] = 'XLFWH' Where [NatureOfFundCode] = 'FWH' And ' to data type int.

1 Answer 1

1

When you are creating the column remainingfilter it has an implicit conversion of int

So to fix that, use ...,cast(NULL as varchar(max)) remainingfilter

That said, I would opt for concat()

Example

Select  Cmd = concat('Update ',quotename(tablename),' set ',quotename(updatecolumn),' = ',updatevalue,' And ' + nullif(remainingfilter,''))
From #Temp

Returns

Update [CRDB_Reporting] set [MagnitudePackage] = 'XLFWH'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.