Use Parameter In OPENROWSET Sql Server

强颜欢笑 提交于 2019-12-20 04:29:06

问题


I am creating an stored procedure in which I am calling an another stored procedure(This procedure is returned lot of columns and I want only one column value So I can't create temp table to store values) using OPENROWSET.

When I am use following then it's alright

declare @AgencyID int=15,@PatientID int=3701
SELECT a.PrimaryInsuredName 
    FROM OPENROWSET('SQLNCLI',  
    'Server=ServerName;Database=DbName;Trusted_Connection=yes',
    'exec USP_Billing_GetPatientWithInsurence 3701,15') AS a;

It's working fine. But I want to pass parameters for calling USP_Billing_GetPatientWithInsurence because values will be dynamic. So I use following code

 declare @AgencyID int=15,@PatientID int=3701
    SELECT a.PrimaryInsuredName 
        FROM OPENROWSET('SQLNCLI',  
        'Server=ServerName;Database=DbName;Trusted_Connection=yes',
        'exec USP_Billing_GetPatientWithInsurence '+ @PatientID +','+ @AgencyID+'') AS a;

But it's not working When I run this query then an error occurred Incorrect syntax near '+'. I don't know why this is coming. Please provide a solution to this. I googled also for this but can't found a proper solution.

Thanks


回答1:


You have to make your entire SELECT string dynamic:

 declare @AgencyID int=15,@PatientID int=3701
DECLARE @SQLStr varchar(max)='
    SELECT a.PrimaryInsuredName 
        FROM OPENROWSET(''SQLNCLI'',  
        ''Server=ServerName;Database=DbName;Trusted_Connection=yes'',
        ''exec USP_Billing_GetPatientWithInsurence '+ CAST(@PatientID AS varchar(15)) +','+ CAST(@AgencyID AS varchar(15)) +''') AS a';
EXECUTE(@SQLStr);


来源:https://stackoverflow.com/questions/30479919/use-parameter-in-openrowset-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!