ScottE
ScottE

Reputation: 21630

Why bother setting the size parameter of a command object parameter?

Our data access layer uses command objects to communicate with sql server.

In most cases I've hard-coded the field size (that matches the column size in sql server) into the command param builder.

Such as:

SqlParameter param = new SqlParameter("@name", NVarChar, 4000);

What's the advantage to specifying a value here (4000 in this example) versus just leaving it as 0? It's a pain when you have to recompile when a column size changes.

Upvotes: 6

Views: 2355

Answers (3)

Remus Rusanu
Remus Rusanu

Reputation: 294387

Is actually quite important. Identical requests issued with different parameter length end up as different queries in the procedure cache. In time, this leads to cache pollution an over-active compilation events. This issue is one of the major design flaws in how both Linq2SQL and the EF providers were implemented, eg. see How Data Access Code Affects Database Performance. Also see Query performance and plan cache issues when parameter length not specified correctly for a related problem.

Upvotes: 5

Philip Kelley
Philip Kelley

Reputation: 40359

If you specify a size that matches the width of the SQL column, then presumably you have another layer that detects and/or prevents data loss. (What happens when a user enters or an application generates more characters than can be stored in the database?)

Perhaps the problem is related to all those Microsoft Buffer Overflows?

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351566

There is no performance or execution-time advantage - size is inferred if it is not explicitly passed:

The Size is inferred from the value of the dbType parameter if it is not explicitly set in the size parameter.

I guess you could say that by explicitly declaring the size of the parameter to match the size of the field in SQL Server you are better informing readers of your code as to the limits of the data model. How useful that may be is in the eye of the beholder.

Upvotes: 2

Related Questions