I'm trying to create a new stored procedure to execute an Alter Database command to modify the database Service Tiers.
So, I've tried to create the stored procedure but It doesn't work and it returns an error
Incorrect syntax near '('.
Could someone tell me how can I do this? Or where is the syntax error?
I've run this one out of any stored procedure and it worked.
Thanks in advance.
create procedure spChangeTiersDB
#MaxSize varchar(8),
#Edition varchar(20),
#Service varchar(5)
as
begin
ALTER DATABASE DB_Name
MODIFY (
MAXSIZE = #MaxSize,
EDITION = #Edition,
SERVICE_OBJECTIVE = #Service)
end
You cannot parameterize ALTER DATABASE statements
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/578d87fa-9939-4cb0-bb72-e37cee8abf25/can-i-pass-parameter-to-an-alter-database-command
As suggested on the MSDN forum link, use Dynamic SQL instead
CREATE PROCEDURE spChangeDBtier
#MaxSize VARCHAR(10),#Edition VARCHAR(10),#Service VARCHAR(10) AS BEGIN
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = CONCAT('ALTER DATABASE dbname MODIFY ( MAXSIZE =',#MaxSize,'GB, Edition = ''',#Edition,''',SERVICE_OBJECTIVE = ''',#Service,''')')
EXEC(#SQL)
END
Sample execution:
spChangeDBtier '500','PREMIUM','P1'
It seems we can't do those changes with something unattended like stored procedures, functions, etc. So, I've made something in C# to change from the server. That's my answer at the moment. If someone else has the same problem here is the code to help.
public static bool ChangeDBTier(string DbName, string MaxSize, string Edition, string Service)
{
try
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
String sqlCommandText = #"ALTER DATABASE " + DbName + " MODIFY (MAXSIZE = " + MaxSize + ", EDITION = '" + Edition + "', SERVICE_OBJECTIVE = '" + Service + "')";
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
return true;
}
catch
{
return false;
}
}
CREATE PROCEDURE #spChangeDBtier
#MaxSize VARCHAR(10),#Edition VARCHAR(10),#Service VARCHAR(10) AS BEGIN
DECLARE #SQL NVARCHAR(MAX)
set #sql = 'alter database test modify(maxsize = '+ #MaxSize + ', edition = ''' + #MaxSize + ''' , service_objective = ''' + #MaxSize + ''')'
EXEC #SQL
END
You can always specify max size but I don't think that is needed as size won't impact billing significantly
Related
I have here a query that select from a local variable. It is working fine with my other stored procedures that didn't have array parameter and when I applied it to this stored procedure it is now not working.
Here is my script below.
AS
DECLARE #serverpath varchar(255)
DECLARE #query varchar(max)
BEGIN
SET #serverpath = (SELECT [path] from [param] where [platform] = 'PLMS')
SET #query='
SELECT
''PLMS'' as PLATFORM,
''PLMS''+ ''0''+ordh_sysrefno as ZINDEX,
ad_sapcode AS "SAP ADVERTISER CODE",
ad_advcde AS "PLMS ADVERTISER CODE",
ad_advnme AS "ADVERTISER NAME",
ag_sapcode AS "SAP AGENCY CODE",
ag_agencde AS "PLMS AGENCY CODE",
ag_agennme AS "AGENCY NAME",
ordh_docno AS "TO NUMBER",
ordh_createdate AS "TO CREATE DATE",
ordh_conttp AS "CONTRACT TYPE",
tt_desc AS "TELECAST TYPE",
'''' AS "PACKAGE TYPE",
'''' AS "REVENUE TYPE",
sapcode as "SAP PROGRAM CODE",
pg_prgcode as "PLMS PROGRAM CODE",
pg_prgname as "PROGRAM",
ordd_teledte AS "TELECAST DATE",
ordd_agencost AS "INTERNAL COST",
ordd_billcost AS "BILLING COST",
''PHP'' AS CURRENCY,
'''' AS PRODUCTION,
spd_cpno as "CP NUMBER",
cph_cpdte as "CP DATE",
cph_prndte as "CP PRINT DATE",
CASE ordh_conttp
WHEN ''C''
THEN spd_invno
WHEN ''X''
THEN spd_exinvno
WHEN ''P''
THEN spd_pbinvno
ELSE '''' END AS "INVOICE NUMBER",
spd_stat as "STATUS"
from
' + #serverpath +'.ord_hdr INNER JOIN
' + #serverpath +'.ord_dtl ON (ordh_sysrefno = ordd_sysrefno) INNER JOIN
' + #serverpath +'.spot_dtl ON (ordd_sysrefno = spd_sysrefno and ordd_dtlno = spd_dtlno ) INNER JOIN
' + #serverpath +'.program ON (pg_prgcode = ordd_prgcode ) INNER JOIN
' + #serverpath +'.advertiser ON (ad_advcde = ordh_advcde) INNER JOIN
' + #serverpath +'.agency ON (ag_agencde = ordh_agencde) INNER JOIN
' + #serverpath +'.cp_hdr ON (ordh_sysrefno = cph_refno and spd_cpno = cph_cpno) INNER JOIN
' + #serverpath +'.cp_dtl ON (cph_cpno = cpd_cpno and cpd_dtlno = ordd_dtlno and cpd_spotno = spd_spotno) FULL OUTER JOIN
' + #serverpath +'.telecast_type ON (ordd_teletp = tt_code) left outer join
PLMSSAP.PLMSSAPSU.programs_season on (platform = ''PLMS'' and pg_prgcode = PLMScode and
cpd_teledte BETWEEN date_start AND date_end)
WHERE
cpd_cpno in (Select LTRIM(RTRIM(StringValue)) FROM #StringAsArray)
'
EXEC (#query)
END
and this is my c# script
public static DataTable SelectFromLocal(string stdproc, string name, DataTable cps)
{
DataTable dt = new DataTable();
dt.TableName = name;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BMSSAP"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(stdproc, con))
{
cmd.CommandType = CommandType.StoredProcedure;
var param = new SqlParameter();
param.SqlDbType = SqlDbType.Structured;
param.Value = cps;
param.TypeName = "StringArray";
param.ParameterName = "#StringAsArray";
cmd.Parameters.Add(param);
cmd.CommandTimeout = 60 * 60 * 60;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
return dt;
}
and I got this error every time I run my application
System.Data.SqlClient.SqlException`: 'Must declare the table variable "#StringAsArray"'.
The problem here is one of scope. Wikipedia has a very detailed definition of scope here. If you want a quick summary, this isn't terrible.
You have dynamic-SQL in your code. By that I mean you are building a SQL statement as a string, and then executing the string using exec().
When you do that, everything inside the exec() is running in its own scope. It can't see any variables that were declared outside of the string you created.
Here's a simple example
declare #var varchar(20) = 'hello'; -- this is in the outer scope
exec
(
'select #var;' -- this will run in its own scope
);
What will happen when I run that? Do I get the result "hello"? No, the variable #var was only declared in the outer scope. In the inner scope it has not been declared. So I get an error:
Must declare the scalar variable "#var".
But just declaring it doesn't help, I want to pass the variable from the outer scope to the inner scope. This won't do what I want:
declare #var varchar(20) = 'hello'
exec('declare #var varchar(20); select #var');
That will run without causing an error, but the result will be null. The #var inside the string is not associated with the #var in the outer scope.
What I need to do is bind the outer #var to the inner one. You can do this with the sp_executesql procedure. THe following code will do what I want. It will output "hello":
declare #var varchar(20) = 'hello';
exec sp_executesql
N'select #var', -- the first argument is the statement I want to run
N'#var varchar(20)', -- the second argument is a comma separated string of parameter definitions
#var; -- the subsequent arguments map the variables from the outer scope to the parameter definitions
I am not going to write out the entire construct for your case, because your dynamic SQL statement is very long. But you have an identical situation. You have a variable which lives in the outer scope as a table valued parameter. You want to send that variable into the scope of the dynamic SQL.
create type dbo.MyStringArray as table (MyString varchar(20));
go
create or alter procedure MyProcedure (#MyTvp dbo.MyStringArray readonly) as
begin
declare #dynamicSQL nvarchar(max) = 'select MyString from #MyTvp';
exec sp_executesql
#dynamicSQL,
N'#MyTvp dbo.MyStringArray readonly',
#MyTvp;
end;
go
-- I can now call this using:
declare #t dbo.MyStringArray;
insert #t values ('hello');
exec myProcedure #t;
NOTE that you must declare the variable which will hold your dynamic SQL as NVARCHAR, not VARCHAR, in order to use sp_executesql. Same with the parameter definitions. If you prefix a literal string with the letter N, it is an nvarchar (as in my example).
I've looked already but what I found so far is exporting to a existing excel sheet, what I need is to make a copy of an existing excel template I have and pass my data there. I just need to be pointed in the right way, hope I'm clear enough.
EDIT
I have an application working on Java to which I will add this.
Assuming that you ask about SQL Server, you can create 2 step job, one for copying your xls, and in second step using openrowset/insert into your copied excel file.
Here is Tsql which copies template and also sends an email, and info about xp_cmdshell https://msdn.microsoft.com/en-us/library/ms190693.aspx
DECLARE #cmd varchar(512)
DECLARE #fd varchar(512)
DECLARE #odbc varchar(128)
DECLARE #db varchar(128)
SELECT #fd = 'D:\Reports\Exact\ByWeek' + CONVERT(VARCHAR(10), GETDATE()-8,120)+'_'+CONVERT(VARCHAR(10), GETDATE(),120)+'.xls'
SELECT #cmd = 'copy D:\Reports\System\shipments_week.xls ' + #fd
EXEC MASTER..XP_CMDSHELL #cmd, NO_OUTPUT
SET #odbc = 'Microsoft.Jet.OLEDB.4.0'
SET #db = 'Excel 8.0;Database=' + #fd
exec('INSERT INTO OPENrowset(''' + #odbc + ''',''' + #db + ''',''SELECT
OrderNr,Debtor,SUM_NSHIPPED,SUM_TOTAL,PERC_NSHIPPED,ORDDAT,INVDAT,ORD_SYSCREATED,HIST_LAST_MODIFIED,PT_WZ_SENT
FROM [Shipped$]'')
SELECT * FROM salag_shipmentsbyWeek')
exec('INSERT INTO OPENrowset(''' + #odbc + ''',''' + #db + ''',''SELECT
OrderNr,Debtor,SUM_NSHIPPED,SUM_TOTAL,PERC_NSHIPPED,ORDDAT,INVDAT,ORD_SYSCREATED,HIST_LAST_MODIFIED,PT_WZ_SENT
FROM [SB$]'')
SELECT * FROM salag_shipmentsbyWeek WHERE Debtor NOT LIKE ''%CASTORAMA%'' AND Debtor NOT LIKE ''Praktiker%''')
DECLARE #Body VARCHAR(4096)
DECLARE #BodyType VARCHAR(16)
DECLARE #path VARCHAR(128)
DECLARE #f VARCHAR(32)
DECLARE #topic VARCHAR(128)
SELECT #f = CONVERT(VARCHAR(10), GETDATE()-8,120)+'_'+CONVERT(VARCHAR(10), GETDATE(),120)
SELECT #topic = 'New Report ['+ CONVERT(VARCHAR(10), GETDATE()-8,120)+'_'+CONVERT(VARCHAR(10), GETDATE(),120) + ']'
SELECT #path = '\\appsrv\Reports\Exact\ByWeek' + CONVERT(VARCHAR(10), GETDATE()-8,120)+'_'+CONVERT(VARCHAR(10), GETDATE(),120)+'.xls'
SELECT #Body = 'New Scan Report has been created: '+#f+' '+ #path
SELECT #BodyType = 'HTMLBody'
exec sp_send_cdosysmail 'Reports Info ','reports#foo ar.com',#topic, #Body, #BodyType
I was able to achieve what I was looking for using JExcel and it was pretty easy, here I will share my code and hope it helps someone in the future. Sorry its not properly commented yet, I will later post an update.
Db_Connect connection = new Db_Connect();
conn = connection.connect();
String originalFile = "C:\\Users\\Geni\\Desktop\\Book1-Template-new.xls";
date = date.replace("/", "-");
SimpleDateFormat myDate = new SimpleDateFormat("yyyy-MM-dd");
try{
Workbook original = Workbook.getWorkbook(new File(originalFile));
WritableWorkbook copy = Workbook.createWorkbook(new File(date+".xls"), original);
java.util.Date format = myDate.parse(date);
java.sql.Date newDate = new java.sql.Date(format.getTime());
String sql = "SELECT Name, sporecount.* FROM sporesfungi "
+ "INNER JOIN sporecount ON sporesfungi.IDSpore = sporecount.IDSpore"
+ "WHERE Date = ? ORDER BY TraceNum";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setDate(1, newDate);
rs = statement.executeQuery();
/*stmt = conn.createStatement();
rs = stmt.executeQuery(sql);*/
WritableSheet sheet = copy.getSheet(0);
WritableCell cell;
String spore;
while(rs.next()){
for(int i = 2; i < 64 ;i++){
cell = sheet.getWritableCell(1,i);
spore = cell.getContents();
if(rs.getString("Name").equals(spore)){
Number l1 = new Number(14-rs.getInt("TraceNum"),i,rs.getInt("Amount")) ;
sheet.addCell(l1);
}
}
}
copy.write();
copy.close();
original.close();
}
catch (BiffException | IOException e) {
}
SELECT TOP #columnCount #columnName
FROM #tableName
I get the following error
Incorrect syntax near '#columnCount'.
What could be wrong?
If I change to
SELECT TOP (#columnCount) #columnName
FROM #tableName
I get the following error
Must declare the table variable "#tableName".
I run it from C#
A safe and secure way would be
DECLARE #columnCount INT = 100
DECLARE #columnName NVARCHAR(128) = 'YourColumnName'
DECLARE #tableName NVARCHAR(128) = 'YourTableName'
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N'SELECT TOP (#columnCount) ' + QUOTENAME(#columnName) + N'
FROM ' + QUOTENAME(#tableName)
EXECUTE sp_executesql #Sql
,N'#columnCount INT'
,#columnCount
You need dynamic SQL to accomplish what you're trying to do.
DECLARE #sql VARCHAR(max);
SET #sql = 'SELECT TOP ' + #columnCount + ' ' + #columnName + ' FROM ' + #tableName;
EXEC(#sql);
The variables used need to be converted appropriately.
Read more in the documentation
Column lists and Table names cannot be parameters. However, since you are running this from C# you are technically already using Dynamic SQL (unless you are calling a stored procedure with those params but there is no mention here of stored procedures being used so for now I will assume not). When building the SQL in C#, you need to concatenate the Column List and Table Name into the query but you can still use a parameter for the value used by the TOP() operator:
SqlConnection _Connection = new SqlConnection("connection string");
SqlCommand _Command = new SqlCommand();
SqlDataReader _Reader = null;
string _Query;
string _TableName = "dbo.MyTable";
string _ColumnList = "Field1, Field2 AS [AliasedName], Field3";
int _NumberOfRows = 12;
_Query = String.Concat("SELECT TOP (#NumberOfRows) ",
_ColumnList, " FROM ", _TableName);
SqlParameter _NumRows = new SqlParameter("#NumberOfRows", SqlDbType.Int);
_NumRows.Value = _NumberOfRows;
try
{
_Connection.Open();
_Reader = _Command.ExecuteReader();
// do stuff
}
finally
{
_Reader.Close();
_Connection.Close();
}
Of course, you could also just concatenate the #NumberOfRows value directly into the query as well, but keeping it as a parameter will allow for Query Plan re-use if running this query multiple times with the same values for ColumnList and TableName but changing the #NumberOfRows value.
Aim: To change the field being updated based on an incoming value from the .aspx.vb code
Issue: I believe that the above Aim works, however I am getting an error on the PropertyID (which is alphanumeric) as it says Invalid column name 'S7753' in this case I was updating PropertyID S7753.
.aspx.vb code:
command.CommandText = "spActionUpdateOldestDate"
command.CommandType = CommandType.StoredProcedure
Dim vCheck As String = Session.Item("PropertyID").ToString & "-" & Session.Item("SafeGuardingDate").ToString & "-" & Session.Item("ActionsFieldName").ToString
command.Parameters.AddWithValue("#PropertyID", Session.Item("PropertyID").ToString)
command.Parameters.AddWithValue("#SafeGuardingDate", Session.Item("SafeGuardingDate").ToString)
command.Parameters.AddWithValue("#ActionsFieldName", Session.Item("ActionsFieldName").ToString)
command.ExecuteNonQuery()
command.Parameters.Clear()
Stored Procedure
USE [DB]
GO
/****** Object: StoredProcedure [dbo].[spActionUpdateOldestDate] Script Date: 04/02/2014 14:24:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spActionUpdateOldestDate]
-- spActionUpdateOldestDate '1234','date','field'
-- Add the parameters for the stored procedure here
#PropertyID nvarchar(50)
,#SafeGuardingDate nvarchar(MAX)
,#ActionsFieldName varchar(MAX)
AS
BEGIN
-- add selection for courseID etc.. here
-- print 'UPDATE [TblActionsOldest] SET ' + #ActionsFieldName + ' = ''' + #SafeGuardingDate + ''' WHERE PropertyID = ''' + #PropertyID+ ''''
Execute ('UPDATE [TblActionsOldest] SET ' + #ActionsFieldName + ' = ''' + #SafeGuardingDate + ''' WHERE PropertyID = ''' + #PropertyID+ '''')
add this line before you add the parameters
SqlCommandBuilder.DeriveParameters(command)
Answer at the top, it was syntax for the PropertyID string.
I am working on a search query (with an asp.net 3.5 front end) which seems quite simple, but is quite complex.
The complete query is:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[usp_Item_Search]
#Item_Num varchar(30) = NULL
,#Search_Type int = NULL
,#Vendor_Num varchar(10) = NULL
,#Search_User_ID int = 0
,#StartDate smalldatetime = NULL
,#EndDate smalldatetime = NULL
AS
DECLARE #SQLstr as nvarchar(4000)
Set #SQLstr = 'SELECT RecID, Vendor_Num, Vendor_Name, InvoiceNum, Item_Num,
(SELECT CONVERT(VARCHAR(11), RecDate, 106) AS [DD MON YYYY]) As RecDate, NeedsUpdate, RecAddUserID FROM [tbl_ItemLog] where 1=1 '
IF (#Item_Num IS NOT NULL and LTRIM(#Item_Num) <> '')
Begin
If #Search_Type = 0
BEGIN
Set #SQLstr = #SQLstr + 'AND Item_Num LIKE ''' + #Item_Num + '%'''
END
If #Search_Type = 1
BEGIN
Set #SQLstr = #SQLstr + 'AND Item_Num LIKE ''%' + #Item_Num + '%'''
END
If #Search_Type = 2
BEGIN
Set #SQLstr = #SQLstr + 'AND Item_Num LIKE ''%' + #Item_Num + ''''
END
End
IF (#Vendor_Num IS NOT NULL and LTRIM(#Vendor_Num) <> '')
Begin
Set #SQLstr = #SQLstr + ' AND Vendor_Num = ''' + #Vendor_Num + ''''
End
IF (#Search_User_ID IS NOT NULL and #Search_User_ID > 0)
Begin
Set #SQLstr = #SQLstr + ' AND RecAddUserID = ' + convert(nvarchar(20),#Search_User_ID)
End
Set #SQLstr = #SQLstr + ' AND (RecDate BETWEEN ''' + convert(nvarchar(10),#StartDate,106) + ''' AND ''' + convert(nvarchar(10),#EndDate,106) + ''')'
PRINT (#SQLstr)
--Execute (#SQLstr)
When I pass all empty parameter values, I get an error:
"Failed to convert parameter value
from a String to a Int32."
The asp.net code that is calling the stored proc is:
//Display search results in GridView;
SqlConnection con = new SqlConnection(strConn);
//string sqlItemSearch = "usp_Item_Search";
SqlCommand cmdItemSearch = new SqlCommand(sqlItemSearch, con);
cmdItemSearch.CommandType = CommandType.StoredProcedure;
cmdItemSearch.Parameters.Add(new SqlParameter("#Item_Num", SqlDbType.VarChar, 30));
cmdItemSearch.Parameters["#Item_Num"].Value = txtItemNumber.Text.Trim();
cmdItemSearch.Parameters.Add(new SqlParameter("#Search_Type", SqlDbType.Int));
cmdItemSearch.Parameters["#Search_Type"].Value = ddlSearchType.SelectedItem.Value;
cmdItemSearch.Parameters.Add(new SqlParameter("#Vendor_Num", SqlDbType.VarChar, 10));
cmdItemSearch.Parameters["#Vendor_Num"].Value = txtVendorNumber.Text.Trim();
cmdItemSearch.Parameters.Add(new SqlParameter("#Search_User_ID", SqlDbType.Int));
cmdItemSearch.Parameters["#Search_User_ID"].Value = ddlSeachUser.SelectedItem.Value;
if (!string.IsNullOrEmpty(txtStartDate.Text))
{
cmdItemSearch.Parameters.Add(new SqlParameter("#StartDate", SqlDbType.DateTime));
cmdItemSearch.Parameters["#StartDate"].Value = Convert.ToDateTime(txtStartDate.Text.Trim());
}
else
{
cmdItemSearch.Parameters.Add(new SqlParameter("#StartDate", SqlDbType.DateTime));
cmdItemSearch.Parameters["#StartDate"].Value = Convert.ToDateTime("01/01/1996");
}
if (!string.IsNullOrEmpty(txtEndDate.Text))
{
cmdItemSearch.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.DateTime));
cmdItemSearch.Parameters["#EndDate"].Value = Convert.ToDateTime(txtEndDate.Text.Trim());
}
else
{
cmdItemSearch.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.DateTime));
cmdItemSearch.Parameters["#EndDate"].Value = Convert.ToDateTime(DateTime.Now);
}
con.Open();
SqlDataAdapter ada = new SqlDataAdapter(cmdItemSearch);
DataSet ds = new DataSet();
ada.Fill(ds);
gvSearchDetailResults.DataSource = ds;
gvSearchDetailResults.DataBind();
pnlSearchResults.Visible = true;
How can I resolve this?
You're not quite building the string correctly as far as I can tell. If no #Item_Num is passed in, you'll end up with no WHERE key word... you'll just have "FROM [tblItem_Log] AND..."
I would make all of the criteria appends be "AND ..." and as your initial statement use:
FROM [tbl_Item_Log] WHERE (1=1)
Since you have code to return the generated string, why not put that into SSMS and try to run it?
I also just noticed that if you don't pass in date values that you will end up executing a NULL string, because your final concatenation will end up causing a NULL. These are the kinds of things that you need to pay very close attention to if you're going to be using dynamic SQL to build queries.
Once I corrected that I was able to run the stored procedure without any errors (at least to generate what looks like a valid SQL statement). That leads me to believe that it may be a problem with data types in the underlying table. Can you provide the definition for that?
One last note: Personally, I would use
CONVERT(VARCHAR(11), RecDate, 106) AS RecDate
instead of the seemingly unnecessary subquery that you have.
Yet another edit:
You may want to remove the code that checks LTRIM(#Search_User_ID) <> ''. It's a pointless bit of code and perhaps a setting particular to your server/connection is causing it to fail because of the type mismatch.
IF (Search_User_ID IS NOT NULL)
needs an # symbol infront of the variable
You say you are passing empty string in for all variables but one is an int, it can't take an empty string that is not int data. Can't believe I didn;t notice that the first time.
Why don't you use single parameterized query like this:
select
recdid,
Vendor_Num,
Vendor_Name,
InvoiceNum,
Item_Num,
CONVERT(VARCHAR(11), RecDate, 106) as RecDate,
NeedsUpdate,
RecAddUserID
FROM
[tbl_ItemLog] as t
where
(((Item_num like #Item_Num + '%' and #Search_Type = 0) OR
(Item_num like '%' + #Item_Num + '%' and #Search_Type = 1) OR
(Item_num like '%' + #Item_Num + '%' and #Search_Type = 2))
OR
#Item_Num IS NULL) AND
(Vendor_Num = #Vendor_Num OR #Vendor_Num IS NULL) AND
(RecAddUserId = #Search_User_Id OR #Search_User_Id IS NULL) AND
(RecDate BETWEEN #StartDate AND #EndDate)
You really have several different stored procedures here. Why not just write them separately? Everything that's controlled by switch statements could be easily in procedural code. Same for the LTRIM calls.
You could call them all from a single SP with switch statements; but I think it's generally better to not merge them in the first place. The SP queries will optimize more easily, and the code will be simpified. There's not much you gain by consolidating them.
Not sure of your business rules, but you could simplify this outside SQL with
switch(search_type) {
case 1:
do_query_type_1(args);
break;
case 2:
do_query_type_2(args);
break;
case 3:
do_query_type_3(args);
break;
default:
whatever ...
}
Also it looks like you have separate logic for cases where the item number is provided or not. Same for other fields. Each of your use cases looks like it resolves to a pretty simple query.