Can I pass a String to a Stored Procedure that is not a Column Name?
I need to call the StoredProcedure from C#.
The following does not work as the parameter can't be defined without it's Type, but shows what I am trying to do. Problem is that Sql is looking at @stringToIdentifyDataTable as a ColumnName, which seems fair, but not what I am trying to do.
Alter PROCEDURE [dbo].[PutNewTypeSource] @stringToIdentifyDataTable,
@ID int, @Description varchar(50), @Active bit
AS
DECLARE
@Query AS VARCHAR(MAX),
@Field_Out AS VARCHAR(MAX)
SELECT @Field_Out = CASE @stringToIdentifyDataTable
WHEN 'ReferralSource' THEN '[Adm].[JobReferralSource]'
WHEN 'ReferralSource2' THEN '[Adm].[JobReferralSource2]'
END
SET @Query = concat('
IF EXISTS (SELECT ID FROM ',@Field_Out,' WHERE Description= ',@Description,')
BEGIN
UPDATE ',@Field_Out,
'SET Active = ',@Active,
'WHERE Description= ',@Description,';
END')
EXEC (@Query)
exec [PutNewTypeSource] 'ReferralSource', 1, 'Description1', 0
If I understand correctly what you could do is this. note that I properly quote your object, and importantly parametrise you parameters. What you have before was wide open to injection:
ALTER PROCEDURE [dbo].[PutNewTypeSource] @Referral varchar(50), @Description varchar(50), @Active bit --I remvoed @ID as it was never used
AS BEGIN
DECLARE @Schema sysname,
@Table sysname;
SET @Schema = CASE WHEN @Referral IN ('ReferralSource','ReferralSource2') THEN N'adm' END;
SET @Table = CASE @Referral WHEN 'ReferralSource' THEN N'JobReferralSource'
WHEN 'ReferralSource2' THEN N'JobReferralSource2' END;
DECLARE @SQL nvarchar(MAX);
SET @SQL = N'UPDATE ' + QUOTENAME(@Schema) + N'.' + QUOTENAME(@Table) + NCHAR(13) + NCHAR(10) +
N'SET Active = @Active' + NCHAR(13) + NCHAR(10) +
N'WHERE Description= @Description;';
EXEC sp_executesql @SQL, N'@Description varchar(50), @Active bit', @Description = @Description, @Active = @Active;
END;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.