0

I am thinking of storing non-sensitive SQL code in a column of a table. Is this considered an acceptable practice ? If yes, then what would be the best datatype for this ? This code is to be accessed by C# code.

EDIT - I am using SQL server. But, this seems like a generic RDBMS question.

Also, related question - What are the pros and cons to keeping SQL in Stored Procs versus Code

17
  • 2
    2) NVARCHAR(MAX). What you try to accomplish ? Commented Jan 6, 2014 at 21:26
  • 4
    @samyi: there are source control systems that use SQL Server to store the source code. Commented Jan 6, 2014 at 21:27
  • 1
    No, you wouldn't store any extraneous SQL data in another table be it query or creation script. If you need code to be accessed by another language, why not setup a stored routine, function, view, etc? Commented Jan 6, 2014 at 21:28
  • 1
    @blasto At my firm, we use Git and Red Gate's SQL Source Control. Storing SQL in a DBMS is silly. Commented Jan 6, 2014 at 21:34
  • 2
    @blasto: Examples: Team Foundation Server, Plastic SCM Commented Jan 6, 2014 at 21:36

1 Answer 1

4

Use stored procedures for this. They are basically what you describe, but with built-in support for maintenance and security.

You can create a procedure:

CREATE PROCEDURE GetCustomerByID ( @CustomerID varchar(11) )
AS 
BEGIN
    SELECT CustomerName, CustomerAddress
    FROM Customers
    WHERE CustomerID = @CustomerID
END

Then call it from C# by using the EXEC command or by specifying CommandType.StoredProcedure.

SqlCommand sqc = new SqlCommand("GetCustomerByID", con);
sqc.CommandType = CommandType.StoredProcedure;
sqc.Parameters.AddWithValue("@CustomerID", "FOOBAR");

var reader = sqc.ExecuteReader();

If you are calling it from SQL, use EXEC

EXEC GetCustomerByID @CustomerID = 'FOOBAR';

To change it later, use ALTER PROCEDURE or DROP PROCEDURE instead of CREATE PROCEDURE

Sign up to request clarification or add additional context in comments.

3 Comments

Now I have a new challenge - My proc takes parameters, which VIEW cannot. so, I cannot use a view instead. I need to pivot the stored procedure as mentioned here - stackoverflow.com/questions/20960784/…
@blasto - So use a table valued function instead.
@blasto If the stored procedure is being written for this purpose.. why not just return the pivoted result instead? In other words, do the pivot inside the sp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.