Stored Procedure field variable - sql

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.

Related

Alter Database in Stored Procedure

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

How to create RDLC report from dynamic query in SQL Server Express

I can't create the rdlc report from this procedure, I'm using report viewer but when I select the procedure, it doesn't show any column names but my procedure returns 7 columns. How can I create the report please help ? I'm creating the report in vb.net
ALTER PROCEDURE Pr_getAcceptedOnDateReport
#date date
AS
SET FMTONLY OFF
DECLARE #SQL varchar(MAX)
DECLARE #antiHIV bit
DECLARE #HBsAg bit
DECLARE #IGMHBCore bit
DECLARE #NAT bit
DECLARE #Malaria bit
DECLARE #TotalHBCore bit
DECLARE #Syphilis bit
DECLARE #HCV bit
DECLARE #ICT bit
DECLARE #DCT bit
DECLARE #Antibody bit
Select #antiHIV=[HIV1/2 screen Reactive],
#IGMHBCore=[IgM HBcore Reactive],
#HBsAg=[HBsAg Screen Reactive],
#NAT= [NAT Reactive],
#Malaria=[Malaria Screen Reactive],
#TotalHBCore=[Total HBcore Reactive],
#Syphilis=[Syphilis Screen Reactive],
#HCV=[HCV screen Reactive],
#ICT=[ICT Positive],
#DCT= [DCT Positive],
#Antibody= [Antibody Screen Positive]
from m_rejectionRules where deleted=0
DECLARE #sql1 nvarchar(4000)
Select #sql1='Select t.donorid, t.donorname, t.sampleid, t.customid,t.bagtype,t.bagnumber, t.segmentno from ttidetail t, m_donor m
where t.donorid=m.donorid
AND CONVERT(date, m.RDate) =''' + cast(#date as varchar(100)) + ''''
IF #antiHIV='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.antiHIV like ' + ''''+ 'Non%Reactive'+''''
END
IF #HBsAg='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.HBsAg like '+ ''''+ 'Non%Reactive'+''''
END
IF #IGMHBCore='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.IGM_antiHBC like '+ ''''+ 'Non%Reactive'+''''
END
IF #NAT='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.NAT_HIV1 like '+ ''''+ 'Non%Reactive'+''''
END
IF #Malaria='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.malariaScreen like '+ ''''+ 'Non%Reactive'+''''
END
IF #TotalHBCore='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.totalAnti_HBC like '+ ''''+ 'Non%Reactive'+''''
END
IF #Syphilis='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.SyphilisScreen like '+ ''''+ 'Non%Reactive'+''''
END
EXEC sp_executesql #sql1
Create a class which maps to your fields returned by your stored procedure
Public Class ReportData
Property donorid AS Integer = 0
Property donorname as string = string.empty
Property sampleid as integer = 0
Property customid as integer = 0
Property bagtype as string = string.empty
Property bagnumber as integer = 0
Property segmentno as integer = 0
End Class
Assuming that you have a function which returns a dataset using the above query, I will refer to it as ds
* MOST IMPORTANT *
When creating your rdlc report instead of mapping to the storedprocdure map it to an object datasource and select the class you just created. Use the fileds in this class as fields for your report.
In the button show report you can use the following code to display your report
Private Sub ShowReport()
Dim dsL As DataSet = New DataSet()
dsL = GetReportData() ' Function which will get the data from the SQL Query
Dim rds As ReportDataSource = New ReportDataSource()
rds.Name = "ReportDS" ' Change to what you will be using when creating an objectdatasource
rds.Value = dsL.Tables(0)
With rvReport ' Name of the report control on the form
.Reset()
.ProcessingMode = ProcessingMode.Local
.LocalReport.DataSources.Clear()
.Visible = True
.LocalReport.ReportPath = reportPath
.LocalReport.DataSources.Add(rds)
' If you have any parameters you can pass them here
Dim rptParameters As New List(Of ReportParameter)()
With rptParameters
.Add(New ReportParameter("Title",
String.Format("{0} Grid For Period {1} To {2}",
gridType,
FormatDateTime(startDate, DateFormat.ShortDate),
FormatDateTime(endDate, DateFormat.ShortDate))))
.Add(New ReportParameter("SubTitle", String.Format("Program: {0}", ucProgram.Text)))
.Add(New ReportParameter("StartDate", startDate))
.Add(New ReportParameter("EndDate", endDate))
End With
.LocalReport.SetParameters(rptParameters)
.RefreshReport()
End With
End Sub

Dynamic sql stored procedure update query issue?

I've written the below code to set filepath column in my table as 'F:\DataMigration\Wise\DELTA_20121008\Attachments\SR\SR_1.txt'
where SR_1 is file_name column
.txt is file_ext column from my table.
but after executing following procedure, I'm getting filepath column in table as
'F:\DataMigration\Wise\DELTA_20121008\Attachments\file_name.file_ext'
means It's treating column names as string, how i can make it as column so it will
use values in that column.
alter procedure [dbo].[WISEMissingAttachmentReportGenerator]
(
#tablename varchar(255), #pathonlocal nvarchar(255)
)
as
begin
--step 1
exec dbo.proc_alter_table #tablename
--step 2
EXEC ('update '+ #tablename +
' set filepath = '''+ #pathonlocal + ' file_name'+'.'+'file_ext''')
EXEC('Select * from '+#tablename)
end
exec [dbo].[WISEMissingAttachmentReportGenerator] [WISE.Non_VP_Service_Request_Attachments_File_Check_Analysis],
N'F:\DataMigration\Wise\DELTA_20121008\Attachments\SR\'
Try;
EXEC('UPDATE '+ #tablename +
' SET filepath = '''+ #pathonlocal + ''' + file_name + '''+'.'+''' + file_ext')
Equal as;
UPDATE [YourTable] SET filepath = 'YourPath' + file_name + '.' + file_ext
Try changing your statement to this:
EXEC ('update '+ #tablename +
' set filepath = '''+ #pathonlocal + ''' + file_name + ''.'' + file_ext')
declare #tblnm varchar(20) = 'test'
declare #upda varchar(20) = 'update '
declare #set varchar(25) = ' set'
declare #id varchar(25) = ' id'
declare #cmd varchar(1000)
set #cmd = #upda + #tblnm + #set + #id + '=7'
exec(#cmd)
SAMPLE SQL UPDATE QUERY - FOR BUILDING TABLENAME DYNAMICALLY
EXECUTED GUYS - THIS IS CALL JUGAAAAAAAAAD [NO NEED TO GET INTO ''' STUFF]

best approach to execute a dynamic query inside a SP

I'm having some trouble executing a dynamic query inside my SP, and I thought asking for some help as I can't execute it correctly no matter what I try:
I have tried:
SET #subWorksQuery =
'UPDATE JK_SubscriberWorks SET ' +
'update_date = convert(datetime, ''' + #dateNow + ''', 103), ' +
'challenge_' + convert(nvarchar(2), #challengeDay) + '_q = ''' + #challengeQuestion + ''', ' +
'challenge_' + convert(nvarchar(2), #challengeDay) + '_a = ''' + #challengeAnswer + ''' ' +
'WHERE subscriberwork_id = '' + convert(nvarchar(10), #subscriberWorksId) + '';';
execute #execReturn = #subWorksQuery
but I always get:
Msg 203, Level 16, State 2, Procedure sp_InsertChallengeResponse_test,
Line 112
The name 'UPDATE JK_SubscriberWorks SET update_date = convert(datetime, '23-12-2011 23:35:17', 103), challenge_23_q =
'Hvilket år blev Klasselotteriet omdannet til et aktieselskab? Få hjælp til svaret.',
challenge_23_a = '1992' WHERE subscriberwork_id = ' +
convert(nvarchar(10), #subscriberWorksId) + ';' is not a valid
identifier.
Removing the UPDATE statement from that error and run it independently, it runs and performs the update
If I use sp_executesql like
SET #subWorksQuery =
N'UPDATE JK_SubscriberWorks SET ' +
'update_date = #a, ' +
'challenge_' + convert(nvarchar(2), #challengeDay) + '_q = #b, ' +
'challenge_' + convert(nvarchar(2), #challengeDay) + '_a = #c ' +
'WHERE subscriberwork_id = #d;';
SET #parmDefinition = N'#a datetime, #b nvarchar(250), #c nvarchar(500), #d decimal';
execute sp_executesql
#subWorksQuery,
#parmDefinition,
#a = #CreateDate, #b = #challengeQuestion, #c = #challengeAnswer, #d = #subscriberWorksId;
It never performs the UPDATE, but does not throw any error.
What am I missing here?
Run it like this:
execute (#subWorksQuery)
[you won't be getting anything back from the update statement in the variable, and you can't run like this execute (#execReturn = #subWorksQuery) ]
Without parentheses it seems to be starting parsing, assuming it is a stored procedure name, but failing when it hits the max length for one.
In saying that, it is better to use sp_executesql with parameters.
I am not sure what you are looking for in the return value, but if you just need the count of rows affected, that should be easy to obtain.
Change:
execute #execReturn = #subWorksQuery
to:
execute (#subWorksQuery)
select #execReturn = ##ROWCOUNT
just a thought...your #d parameter is a decimal value. Is your id an int? is there a possible data type conflict?
how are your sp input parameters defined? Could you post the full sp?
Dave

Parameterizing Dynamic SQL issue with SQL_VARIANT datatype

I've been refactoring a huge dynamic SQL statement, and think I may have hit a roadblock. The goal has been to parameterize it. I'm using SQL Server 2005.
I have an int variable (#i) that determines what column I need to update. Here's what I've been doing:
if #i = 1
begin
set #updateClause = 'Column1 = #newValue';
set #updateClauseDataType = 'varchar(10)';
set #updateValue = #foo;
end
else if #i = 2
begin
set #updateClause = 'Column2 = #newValue';
set #updateClauseDataType = 'int';
set #updateValue = #bar;
end
else if ...
Then, I try to execute my statement:
set #statement = N'update ' + #server_name + '.' + #database_name + '.dbo.Table1
set ' + #updateClause + ' where pk = #pk';
set #parameters = '#newValue ' + #updateClauseDataType + ',
#pk uniqueidentifier';
execute sp_executesql #statement,
#parameters,
#newValue = #newValue,
#pk= #pk;
This results in:
Implicit conversion from data type
sql_variant to varchar is not allowed.
Use the CONVERT function to run this
query.
I can get around this if I can somehow cast #updateValue into the correct type, which I have stored as text in #updateClauseDataType. Is there any way I can do this without having a huge if statement that interrogates the value of #updateClauseDataType?
On rereading, since you already know the data type, why not include it in the update clause?
set #updateClause = 'Column1 = cast(#newValue as varchar(10))';
set #updateClauseDataType = 'varchar(10)';
Or to avoid typing the data type twice:
set #updateClauseDataType = 'varchar(10)';
set #updateClause = 'Column1 = cast(#newValue as ' +
#updateClauseDataType + ')';