-3

当前表

EmployeeID  CompanyID   EmployeeCode    EmployeeName
    1001        C001         11919     ABC
    1002        C001         10974         PQR
    1003        C001         11890     XYZ
    1004        C001         11621     LMN

像这样查询...

     DECLARE @Empid VARCHAR(MAX)
SELECT @Empid= COALESCE(@Empid +',','')+''''+EmployeeID+'''' FROM cmsEmployee WHERE employeeCode IN('11919','10974','11890','11621' )
print @Empid
SELECT * FROM cmsEmployee WHERE EmployeeID IN( @Empid)

这不起作用,为什么?

4

3 回答 3

3

它不起作用,因为您不能将单个字符串放入in子句并期望引擎解析它。

您只能像在第一个查询中使用它时那样放入多个单个值。

where id in ('1','2')  -- works beause that are two SEPERATE values
where id in ('1,2')    -- works not because it is ONE string
于 2013-10-19T11:16:30.190 回答
0

If you are in SQL Server you likely need to use dynamic sql; that needs you to build your query up as a string then execute it when its complete

Change your empid declaration to

  DECLARE @Empid VARCHAR(MAX) = 'SELECT * FROM cmsEmployee WHERE EmployeeID IN( '

When you have selected it add a close bracket (you could build the string up in steps if you want to.)

select @empid = @empid + ')'

If you take your print statement it should run when you have it right; to run it in your code

exec sp_exectutesql @empID
于 2013-10-19T11:39:04.040 回答
0

如果您编写一个由多个部分组成的直接查询,则不应忘记添加 GO 来执行每个部分。

Select ... 
GO
Print ... 
GO
Select ... 
于 2013-10-19T11:18:48.107 回答