I have SQL Server stored procedure with a table-valued parameter
CREATE TYPE T_WORD AS TABLE
(
SWC_Index INT IDENTITY,
SWC_Value VARCHAR(MAX)
)
CREATE PROCEDURE SP_LOG
@i_msg VARCHAR(4000) ,
@i_word T_WORD READONLY
AS
BEGIN
SET IMPLICIT_TRANSACTIONS ON
declare @i int
SET @i = 1
while (@i <=(SELECT COUNT(*) FROM @i_word))
begin
INSERT INTO LG_REPORT
values(@i_msg,(select SWC_Value from @i_word where SWC_Index = @i))
end
IF @@TRANCOUNT > 0
COMMIT
END
And I need to write a C# CLR wrapper that simply executes this procedure in a new connection.
C# code looks like this
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
namespace SQLCLR
{
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void exec_SP_LOG(Object i_msg, Object i_word)
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
SqlCommand Command = new SqlCommand();
SqlParameter i_msgParam = new SqlParameter("@i_msg", SqlDbType.VarChar);
SqlParameter i_wordParam = new SqlParameter("@i_word", SqlDbType.Structured);
i_wordParam.TypeName = "T_WORD";
i_msgParam.Value = i_msg;
i_wordParam.Value = i_word;
Command.Parameters.Add(i_msgParam);
Command.Parameters.Add(i_wordParam);
Command.CommandText = "exec SP_LOG @i_msg, @i_word";
Command.Connection = connection;
connection.Open();
Command.ExecuteNonQuery();
connection.Close();
}
}
}
}
After adding the dll to SQL Server and creating procedure
CREATE PROCEDURE [dbo].[exec_SP_LOG]
@i_msg sql_variant ,
@i_word sql_variant
AS
EXTERNAL NAME [SQLCLR].[SQLCLR.StoredProcedures].[exec_SP_LOG]
GO
I try to execute this function
declare @typ1 T_WORD
insert into @typ1(SWC_Value) values('djhgfj')
insert into @typ1(SWC_Value) values('dfhdf')
exec exec_SP_LOG 't1', @typ1
However I get the following error
Msg 206, Level 16, State 2, Procedure exec_SP_LOG, Line 0
Operand type clash: T_WORD is incompatible with sql_variant
It looks like something is wrong with datatype of table-valued parameter in C#.
The question is how to pass table-valued parameters properly in C# and therefore what is the proper datatype to be used for calling this extended procedure from SQL Server.
Any help is greatly appreciated.