1

I am using SQL server.

I try to get JSON value from table data in SQL server. In my case I want to get ROOT as what I get from the Declared VARIABLE.

Here is my code:

DECLARE @TpiType VARCHAR(64)='SMS'
 ,@TpiName VARCHAR(24)='PLIVO'
 ,@Purpose VARCHAR(24)='SYSTEM'

DECLARE @Purpose2 VARCHAR(24)

SET @Purpose2=@Purpose +'%'

SELECT Name,Value 
FROM MyTable 
WHERE Type=@TpiType AND Name=@TpiName 
AND NAME LIKE @Purpose2
FOR JSON AUTO,ROOT(@TpiType)

When I try this it shows me the error:

Incorrect syntax near '@TpiType'.

But If I give the string value directly to the root, it works fine. But when I pass the variable, it throws error.

Please help me to fix this issue. Thanks in advance.

1 Answer 1

2

You might find using dynamic sql helpful here:

DECLARE @TpiType VARCHAR(64)='''SMS''' 
 ,@TpiName VARCHAR(24)='''PLIVO'''
 ,@Purpose VARCHAR(24)='''SYSTEM'

DECLARE @Purpose2 VARCHAR(24)

SET @Purpose2=@Purpose +'%'''

Declare @sql VARCHAR(2000)
Set @sql = 'SELECT Name,Value 
FROM MyTable 
WHERE Type=' +@TpiType+' AND 
Name=' +@TpiName +' 
AND NAME LIKE ' +@Purpose2+' 
FOR JSON AUTO,ROOT(' +@TpiType+')'

Print @sql -- check if this prints the sql script correctly
--Exec (@sql) -- run this to execute dynamically created script
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.