Microsoft SQL Server相当于这个MySQL查询

时间:2015-11-25 04:35:53

标签: mysql sql sql-server

所以,我有以下MySQL存储过程,我的任务是在Microsoft SQL中创建相同的过程:

scanner.nextLine();

以下似乎正确解析,但是当它执行时,我收到IF条件的错误。什么是Microsoft SQL的正确语法?

SET @sql = NULL;
SELECT  
  GROUP_CONCAT(DISTINCT
    CONCAT('MAX(IF(Record1 = ''',Record1,''', IsCompatible, NULL)) AS ''',
           CONCAT(pr.ProductName,' ', pr.ProductRelease), '''')
  ) INTO @sql
FROM
  ProductCompatibility pc
  LEFT JOIN Products as pr
       on pr.id = pc.Record1;

SET @sql = CONCAT(
              'SELECT pr.id, CONCAT(pr.ProductName,'' '', pr.ProductRelease) as Product, ', @sql, '
                 FROM ProductCompatibility pc 
                 LEFT JOIN Products as pr
                    on pr.id = pc.Record2 
                 GROUP BY pc.Record2');

PREPARE stmt FROM @sql;
EXECUTE stmt;

任何指针?

2 个答案:

答案 0 :(得分:1)

对于IF错误,如果您使用的是SQL Server 2012或更高版本,请考虑将其更改为IIF,或者对于较低版本,请考虑将其更改为CASE

答案 1 :(得分:0)

经过多一点挖掘后,这是等效SQL Server功能的正确格式:

DECLARE @sql varchar(MAX), @finalsql varchar(MAX)

SET @sql = (SELECT
    dbo.GROUP_CONCAT(DISTINCT CONCAT('MAX(IIF(pc.Record1 = ''',pc.Record1,''', pc.IsCompatible, NULL)) AS ''',
           CONCAT(pr.ProductName,' ', pr.ProductRelease), ''''))
FROM 
    [dbo].[ProductCompatibility] pc LEFT JOIN [dbo].[Products] 
        as pr on pr.id = pc.Record1);

SET @finalsql = CONCAT(
              'SELECT CONCAT(pr.ProductName,'' '', pr.ProductRelease) as Product, ', @sql, ' 
                    FROM ProductCompatibility pc 
                 LEFT JOIN Products as pr
                    on pr.id = pc.Record2
                 GROUP BY pr.ProductName, pr.ProductRelease, pc.Record2');

EXECUTE(@finalsql);

事实证明,我必须在组中添加几个其他列,以便正确显示SQL条目。并且还使用@Revenant解决方案来使用IIF而不是IF。