stored procedure in SQL CLR - c#

How do you write a stored procedure using C# in SQLCLR?
Currently I am using SQL Server Management Studio and I write stored procedures using T-SQL such as create proc sp_item as .....

See:
Building my first SQL CLR stored procedure
CLR Assembly RegEx Functions for SQL Server by Example
Choosing between CLR and T-SQL stored procedures: a simple benchmark
Basically, there are Visual Studio templates which allow you to get started with SQL CLR projects. Fill in the blanks, write your actual code, and you can even deploy those CLR assemblies into SQL Server directly from within Visual Studio.
One word of caution: I would refrain from doing set-based updates and inserts and stuff like that in a SQL CLR stored proc - for that, T-SQL stored procs are just plain better and faster.
SQL-CLR is great to extend SQL Server with stuff like string manipulation, date handling, ability to call e.g. web services or other stuff. I would recommend against trying to replace all T-SQL stored procs with C# SQL CLR stored procs just because you can or just because it's cool - use the right tool for the right job! Mass operations on sets are better left to T-SQL.

In addition to the links provided by Marc, I also wrote a short tutorial on writing SQLCLR Table-Valued Functions (FYI, free registration is required to view articles on SQL Server Central):
CLR Table-Valued Function Example with Full Streaming (STVF / TVF)
I have also been writing a series of articles about working with SQLCLR in general:
Stairway to SQLCLR
Also, you should not use sp_ as a prefix in stored procedure names. That is a special syntax that degrades performance due to causing SQL Server to first check for that stored procedure in master, and then, if not found there, it will search the current database.

Related

Manage SQL Server stored procedures in Visual Studio

It is well known that perfomance wise, it is recommended to use SQL Server stored procedures instead of inline code. However, I still use inline SQL queries in Visual Studio for various reasons:
The queries can be neatly organized in separate text files (.sql) and in a folder structure.
The files are part of the Visual Studio solution and thus submitted to source control.
Changes to SQL queries can be published together with the applications (using WebDeploy for ASP.NET apps or ClickOnce for Windows apps).
There is no need to synchronize changes to the SQL queries and publishing new versions of applications.
It enables me to work on the SQL queries even when I am offline (or without access to that particular SQL Server).
I am not quite ready to give up these advantages but still, I am aware that I am sacrificing performance.
Is there a way to get the best of both worlds?
Thanks in advance for any insights.
Chris
Literally every single one of your points can be provided by Stored Procedures too... Not only could you just have a .sql file with the CREATE or ALTER command for the stored procedure in the exact same way you manage it now, but you could go a step further and use a SQL Database Project type to deploy them in a better manner...
https://msdn.microsoft.com/en-us/library/xee70aty(v=vs.140).aspx
But I will note that stored procedures are not automatically better for performance... If you read this is probably refered to the fact that they are easier to parameterize, so the plans can be resued. Using proper Parameterized queries you will have the same benefits, so I think the basic premise of your question is incorrect.
I still use inline SQL queries in Visual Studio ...
But how? Context is important here. VS is just a tool. If you use inline queries in your app, then you have a potential security risk if you are not careful about how you implement them (re: sql injection). In addition, the use of inline queries requires the appropriate permissions to database objects - another security risk. And this approach creates a dependency between your code and the schema - which is minimized by using procedures.

Procedure or function has too many arguments specified, C# & SQL Server

I am developing my very first stored procedure in SQL Server 2012 and need advice concerning the error message I get.
C# code:
Stored procedure code:
In the example you showed, you are not using the stored procedure. The whole Program.sqlcmd.CommandType isn't being used, as you specify a different SQL string (st) to use.
You need to look at examples of how to do stored procedures from c#.
How to execute a stored procedure within C# program

Stored procedure input validation in EF

I have imported a SQL Server stored procedure into the .edmx file. I'm calling the generated method like:
entity.MySP(stringInput)
Does the stringInput parameter need to be validated (for SQL injections etc) when using EF, or can I assume EF does that for me? If not, is there a method I can call to escape/validate the input parameter?
I'm using SQL Server 2008 R2, .NET 4.0, C#, ASP.NET MVC 4, VS2010.
EDIT:
Note that I'd like to use LINQ instead of calling a SP, but I'm using FREETEXT, so I think this is the more elegant solution.
You can read more about LINQ to Entity Framework Security here, http://msdn.microsoft.com/en-us/library/cc716760.aspx. Look at the section titled "Security Considerations for Queries".
To answer your question specifically, Entity Framework will call your stored procedure and pass in the stringInput value. That means even if stringInput is a SQL statement meant to inject something harmful into your database, just passing it to your stored procedure will not cause a SQL Injection attack.
However, depending on how you use stringInput in your stored procedure, you could still leave yourself open to an attack. Specifically, if you use stringInput in a dynamic SQL statement that you execute, you are leaving yourself open to attack. If you use it to do a compare in the WHERE section of a SELECT statement you should be safe.
It really depends on what you are doing inside of your stored proc. Simply by using stored procs, you are not immune to SQL Injection. Conversely, by using variables in your LINQ to Entity code, you are safe from SQL Injection because the query is parameterized correctly there as well. Unfortunately, full text indexing is not supported in Entity Framework, so you will need to resort to procs or functions to use them for performance concerns. I wouldn't say that it is necessarily more "elegant" than a LINQ generated query however.

Stored Procedures vs Code in Database Query

What are the performance differences between accessing a database to query using ASP.NET Code behind against using SQL Stored Procedure
For ease of use, coding the query is easier, especially when coming to maintenance and changes.
However, a stored procedure is compiled in a database and run by the database.
Which one is more efficient, better to use?
SQL Server caches the execution plan of any query, SPROC or not. There is virtually no difference here. Basically, you save sending the query text over the network when using an sproc, nothing more. Source: http://msdn.microsoft.com/en-us/library/ms181055.aspx
Without and special reason being present, do what ever is more convenient to you.
The other answers suggesting generally better performance for sprocs are not true.
As long as it is a database centric query then the stored procedure will in most times be the faster choice (Performance).
But it is harder to maintain because its not in your regular source bundle.
"Better to use" depends on the requirements. If its okay when the query is a tad slower (like 1 ms VS 3 ms) then keep your code together and have it in ASP. If performance is the thing you want put it in the Database.
I put most of my queries in the code and only the ones that NEED the performance in the database.
Also it depends on the Database System used, of course.
Your question is very incomplete as to what you are actually comparing.
Whether the SQL code is in a stored procedure or a full-blown inline SQL statement submitted from the client usually makes little difference (assuming proper parameterization and the SQL being non-pathological) to performance. It can make a large difference in the security architecture and access required to be given to base tables or views instead of execution rights on procedures. Stored procs encourage parameterization as a requirement, but parameterization is also possible with inline SQL.
If you are talking about performing logic against sets returned from the database versus doing the work in the database, this can go both ways - it depends upon the type of operation, the type of indexing, the bandwidth between client and database and number of requests needed to be serviced.
Usually, I'd look first at doing it in the database to keep the join/looping logic abstracted from the client and reduce data on the wire (both columns and rows) and present a simple data set API to the client, but IT DEPENDS.
This is an "it depends" question.
Presuming this is SQL Server 2008R2 or higher Standard or Enterprise edition, stored procedures will cache differently than a TSQL statement. Complex T-SQL statements will almost always perform worse than a stored procedure due to multiple things such as parameterization, code compilation, parameter sniffing, and various other optimizations. In general, I prefer stored procedures as they are MUCH easier to optimize. Plus you can change a stored proceudre without re-compiling and re-deploying any code. And optimizations (such as "optimize for unknown" or
"with recompile" can be applied to a stored procedure when parameter values vary drastically) can be applied to a stored procedure and un-done without end users even noticing (well, except for a performance change).
A stored procedure will always end up in the plan cache after a single run and will never be considered an ad-hoc query. Ad-hoc queries, depending on SQL settings, may or may not be stored in the plan cache. Plus adding or removing a character (presuming it is not parameterized) will cause SQL Server to build a new plan and building new plans is a slow operation.
TL;DR - preusming SQL Server 2008R2 or higher Standard/Enterprise; for simple queries, you will notice no difference. For complex queries, stored procedure (if written properly) will almost always out perform T-SQL. Stored procedures are easier to optimize at a later date as well.
Edit - added in SQL version. I am uncertain about older SQL versions.

insert directly or via a stored procedure

I am using sql server and winforms for my application. data would be inserted every minute into the database tables by pressing a button on a Form.
for this, I am using the INSERT query.
But if I create a procedure and include the same insert query in it, then would it be more efficient, what would be the difference then?
Using stored procedures is more secure
A stored procedure would generally be quicker as the query plan is stored and does not need to be created for each call. If this is a simple insert the difference would be minimal.
A stored procedure can be run with execute permissions which is more secure than giving insert permissions to the user.
It depends on what you mean by 'efficient'.
Execution time - if you're only saving to the database only every couple of seconds then any speed difference between SPs and INSERT is most likely insignificant. If the volume is especially high you would probably set up something like a command queue on the server before fine-tuning at this level.
Development time
using INSERT means you can write your SQL directly in your codebase (in a repository or similar). I've seen that described as poor design, but I think that as long as you have integration tests around the query there's no real problem
Stored Procedures can be more difficult to maintain - you need to have a plan to deploy the new SP to the database. Benefits are that you can implement finer-grained security on the database itself (as #b-rain and #mark_s have said) and it is easy to decide between INSERT and UPDATE within the SP, whereas to do the same in code means making certain assumptions.
Personally (at the moment) I use inline SQL for querying and deleting, and stored procedures for inserting. I have a script and a set of migration files that I can run against the production database to deploy table and SP changes, which seems to work pretty well. I also have integration tests around both the inline SQL and the SP calls. If you go for inline SQL you definitely should use parameterised queries, it helps against SQL injection attacks and it is also easier to read and program.
If your DBA is even allowing you to do this without a stored procedure I'd be very suspicious...

Categories

Resources