Execute a sql string in sql server

brccelvz  于 2023-10-15  发布在  SQL Server
关注(0)|答案(5)|浏览(130)

My code is as below, somehow there is always an error near @Name

DECLARE @Name nvarchar(MAX)  =  '(mm.dll, ben and jerry.exe)'
DECLARE @sql nvarchar(MAX)= 'SELECT OrderName,
   customer.version,
   count(DISTINCT company.CID) as Counts
FROM [CompanyData] company
  INNER JOIN [vendor] mav on company.CID = mav.CID
  LEFT OUTER JOIN [Customer] customer on company.VendorId = customer.VendorId AND company.DId = customer.DId
WHERE OrderName in' + @Name+ '
  GROUP BY  
         customer.version, OrderName'

EXEC sp_executesql @sql
bksxznpy

bksxznpy1#

Put a single quote in your declaration of @Name and just remove the hashes(#) in it:

DECLARE @Name nvarchar(MAX)='(''mm.dll'', ''ben and jerry.exe'')'
DECLARE @sql nvarchar(MAX)= 
       'SELECT 
              OrderName,
              customer.version,
              count(DISTINCT company.CID) as Counts
        FROM [CompanyData] company
        INNER JOIN [vendor] mav on company.CID = mav.CID
        LEFT OUTER JOIN [Customer] customer on company.VendorId = customer.VendorId    
             AND company.DId = customer.DId
        WHERE OrderName in ' + @Name+ '
        GROUP BY customer.version, OrderName'

EXEC sp_executesql @sql
bq3bfh9z

bq3bfh9z2#

Please add double quotes in @Name variable like..

DECLARE @Name nvarchar(MAX)  =  '("mm.dll", "ben and jerry.exe")'
jmo0nnb3

jmo0nnb33#

it would probably save you a lot of grief if you store your names into a table value;

DECLARE @a varchar(max) = 'Jerry.ede';    
DECLARE @b varchar(max) = 'Sa''ra';    
DECLARE @c varchar(max) =  '(''mm.dll''),(''ben and jerry.exe'')';

DECLARE @Names TABLE (name nvarchar(MAX));

INSERT INTO names values (@a),(@b);
EXEC sp_executesql N'INSERT INTO names values ' + @c;

SELECT OrderName,
   customer.version,
   count(DISTINCT company.CID) as Counts
FROM [CompanyData] company
  INNER JOIN [vendor] mav on company.CID = mav.CID
  LEFT OUTER JOIN [Customer] customer on company.VendorId = customer.VendorId AND company.DId = customer.DId
WHERE OrderName in (SELECT name from @names)
  GROUP BY  
         customer.version, OrderName;
kcugc4gi

kcugc4gi4#

EXEC(@sql) or EXEC sys.sp_executesql @sql

shstlldc

shstlldc5#

Please add double single qoute in the string @name .

DECLARE @Name nvarchar(MAX)  =  '(sally''s order, ben and jerry)'
 DECLARE @sql nvarchar(MAX)= 'SELECT OrderName,
 customer.version,
  count(DISTINCT company.CID) as Counts
 FROM [CompanyData] company
 INNER JOIN [vendor] mav on company.CID = mav.CID
 LEFT OUTER JOIN [Customer] customer on company.VendorId = customer.VendorId       
 AND company.DId = customer.DId
 WHERE OrderName in' + @Name+ '
 GROUP BY  
 customer.version, OrderName'

 EXEC sp_executesql @sql

相关问题