This extended version on my previous question sql Append for value with single quotes which am trying to fix
DECLARE #fNAME varchar(40) = 'O'brain'
DECLARE #query nvarchar(256)
DECLARE #id nvarchar(5) = '8'
SET #query = 'UPDATE TableName SET columnname = ''' + #fNAME + '''' +'Added on '+ GETDATE() + ''' WHERE Id= ' + convert(nvarchar, #id)
am trying to get below output using
EXEC sp_executesql
Update table name set columnname = 'O''brain Added on Aug 8 2017 11:15AM' where id = 8
Basically am trying to append some text and current date along with name to be updates as text in one column
I would define and execute the query as:
DECLARE #fNAME varchar(40) = 'O''brain';
DECLARE #query nvarchar(256);
DECLARE #id nvarchar(5) = '8';
SET #query = '
UPDATE TableName
SET columnname = #fNAME + '' added on '' + convert(varchar(255), GETDATE() )
WHERE Id = #id';
EXEC sp_executesql #query, N'#fname varchar(40), #id nvarchar(5)', #fname=#fname, #id=#id;
Note: This is not going to format the date exactly as in your question. You haven't chosen a formatting for the date in your code, so I didn't either.
Here is how you would do this with a normal update. There appears to be no reason at all to use dynamic sql here.
DECLARE #fNAME varchar(40) = 'O''brain';
DECLARE #id nvarchar(5) = '8';
Update TableName
set columnname = #fNAME + ' added on ' + convert(varchar(255), getdate())
Related
I am facing an issue with running a stored procedure with a Date parameter. I have 2 parameters in a stored procedure which returns a result set from a table. In the table name is of type nvarchar and dateclient is a date.
The value of the parameters are coming from an user interface.
ALTER PROCEDURE [dbo].[NAME_SEARCH]
#name nvarchar(255),
#dateclient datetime
AS
BEGIN
DECLARE #parsed_string nvarchar(max)
EXEC parsing_coi_input #name, #parsed_string OUTPUT
PRINT #parsed_string
SET #name = #parsed_string
DECLARE
#BaseQuery nvarchar(max) = 'SELECT Id, name, date_client
FROM Client
INNER JOIN CONTAINSTABLE (Client, ame,'''+ #name + ''') as name_key ON ID = name_key.[KEY]'
DECLARE
#OrderByQuery nvarchar(max) = ' ORDER BY name_key.RANK'
DECLARE
#OrderDesc nvarchar(max) =' DESC'
BEGIN
SET NOCOUNT ON;
SET #BaseQuery = #BaseQuery + '
INNER JOIN CONTAINSTABLE(Client, date_client,'''+ #dateclient +''') AS
date_clientkey ON ID = date_clientkey.[KEY] WHERE date_client_matter_open >= '+ #dateclientmatter
+''
SET #OrderByQuery = #OrderByQuery + ',date_client_key.RANK'
END
DECLARE #fullQuery nvarchar(max)= #BaseQuery + #OrderByQuery + #OrderDesc
EXECUTE sp_executesql #fullQuery
END
I am executing:
EXEC [dbo].[NAME_SEARCH] 'MGeolo','2009-04-05'
But I get this error:
Conversion failed when converting date and/or time from character string.
Any suggestions how to handle this?
You are missing the ' characters around your date when the SQL script is generated and a cast from datetime to varchar.
You should do like:
BEGIN
SET NOCOUNT ON;
SET #BaseQuery = #BaseQuery + '
INNER JOIN CONTAINSTABLE(Client, date_client,'''+ cast(#dateclient as varchar(200)) +''') AS
date_clientkey ON ID = date_clientkey.[KEY] WHERE date_client_matter_open >= '''+ cast(#dateclientmatter as varchar(200)) +''''
SET #OrderByQuery = #OrderByQuery + ',date_client_key.RANK'
It is probably a typo but the #dateclientmatter is undeclared because in the header you have only #dateclient.
I have table with columns Char1, Char2, Char3..... Each of these columns contain some value. I declared variable #i and in while loop I'm trying to concat it to the Char table column name.
Also, I declared parameter #current in my query and then I'm trying to set its value in the query.
set #tmp = cast(#i as varchar(2))
select #current = 'Char' + #tmp
from SerialNumberFormat
where Example = 'XXXXXXXXXX'
When I execute the query #current has value Char1, Char2, Char3...etc, instead the value of the column.
How I can set column value instead column name in #current?
select #current = Concat(Char1, Char2, Char3)
from SerialNumberFormat
where Example = 'X59AA419010045'
Solution which I found and works for me is executing sp_executesql stored procedure
set #SQL = N'select #currentOUT = Char' + #tmp + ' from SerialNumberFormat
where Example = ''XXXXXXXXX'''
SET #ParmDefinition = N'#currentOUT nvarchar(10) OUTPUT'
exec sp_executesql #SQL, #ParmDefinition, #currentOUT = #current OUTPUT
select #current
Dynamic Sql like this may work for you
Declare #i int = 5
Declare #tmp varChar (10) = #i
Declare #Sql nVarChar(Max) = 'select Char' + #tmp + '
from SerialNumberFormat
where Example = ''X59AA419010045'''
exec sp_executesql #Sql
I'm trying to get a few values from a dynamic SELECT
This is my code:
DECLARE #sqlCommand varchar(1000)
DECLARE #colName varchar(20)
DECLARE #tableName varchar(20)
DECLARE #myNum int
DECLARE #varDate varchar(19)
DECLARE #myTime datetime2
set #varDate = getdate()
SET #colName = 'col1'
SET #tableName = 'table'
SET #sqlCommand = 'SELECT top 1 #myTime=mytime, #myNum=' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
PRINT #sqlCommand
EXEC(#sqlCommand)
When I print the SQL command, this is what I get:
SELECT top 1 #myTime=mytime, #myNum=col1
FROM table
WHERE mytime>='Jul 25 2017 4:40PM'
ORDER BY mytime
When I try to EXEC it, I get this error:
Must declare the scalar variable "#myTime".
If I do this:
SET #sqlCommand = 'SELECT top 1 mytime, ' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
It works well, but I need to use that data.
Thanks in advance.
Use sp_executesql:
exec sp_executesql #sqlCommand,
N'#myNum int output, #myTime datetime2 output, #vardate datetime2',
#myNum = #myNum output,
#myTime = #myTime output,
#vardate = #vardate;
This is a much better way to run SQL code, because handling parameters is built-in.
Simple...use the Variable passing features, make to identify the Output variables last in the list of variables
Rough signature but should get you started #o_sdate, #o_edate, and #o_resp are variables declared outside of the dynamic sql
exec sp_executesql #sql
, N'#sdate date, #edate date, #resp smallint OUTPUT'
, #sdate = #o_sdate, #edate = #o_edate, #resp = #o_resp OUTPUT
You should use "insert exec" to get your variable out off the dynamic sql. Or use a "double-hash"-table.
DECLARE #sqlCommand varchar(1000)
DECLARE #colName varchar(20)
DECLARE #tableName varchar(20)
DECLARE #myNum int
DECLARE #varDate varchar(19)
DECLARE #myTime datetime2
set #varDate = getdate()
SET #colName = 'col1'
SET #tableName = 'table'
SET #sqlCommand = 'SELECT top 1 mytime, ' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
PRINT #sqlCommand
create table #t1 (mytime datetime, col1 varchar(20))
insert #t1 (mytime, col1) EXEC(#sqlCommand)
select #mytime=mytime, #col1=col1 from #t1
I hope you got the idea.
I want to set a variable to the value generated using the dynamic query outside the query.
I tried the sp_executesql concept, but this does not help me because I am using the parameter value in the dynamic query.
Are there any possibilities to fix this issue?
CREATE PROCEDURE [dbo].[SP_test_proc]
#id int = null,
#deptId int = null
As
BEGIN
DECLARE #Condition VARCHAR(MAX),#Query NVARCHAR(MAX)
SET #Condition= 'Where Id = '#id + case when #deptid is null then '' else #deptid End
SET #Query = 'Declare #Name varchar(100)
Set #Name = Select name from student '+ #Condition
SELECT *
FROM personal
WHERE name = #Name
END
Use output parameter in dynamic sql as shown here
Also see this
Try this :
DECLARE #Condition VARCHAR(MAX),#Query NVARCHAR(MAX)
SET #Condition= 'Where Id = '#id + case when #deptid is null then '' else #deptid End
Declare #Name varchar(100),#nameval varchar(100),#paramdef varchar(100)
SET #Query = '
Select #Name = name from student '+ #Condition
set #paramdef=N'#Name varhcar(20) OUTPUT'
execute sp_executesql #Query,#paramdef,#Name=#nameval Output
SELECT *
FROM personal
WHERE name = #nameval
Hope this code will work for you.
CREATE PROCEDURE [dbo].[SP_test_proc]
#id int = null,
#deptId int = null
As
BEGIN
DECLARE #Condition VARCHAR(MAX),#Query NVARCHAR(MAX)
SET #Condition= 'Where Id = ' + #id + ' And [Deptid] = ' + ISNULL(#deptid,'')
SET #Query = 'SELECT * FROM personal WHERE name IN ( SELECT name FROM student ' + #Condition + ')'
EXEC #Query
END
[Deptid] is not sure I don't know column name
I have a stored procedure for creating inventory transactions that requires the assembly of a description. Since other inventory stored procedures will also need to assemble their descriptions similarly, I am trying to create a helper stored procedure.
This helper will use standard parameters and construct the description. The trouble I am having is returning the string Description back to the inventory transaction.
A Inventory transaction calls the helper this way:
declare #TransDescription nvarchar(256)
declare #TransDescOut nvarchar(256)
EXEC [dbo].[sp_KF_Helpers_CreateInvTransDescription]
#TransactionTypeID, #UserName, #OwnerTypeID, #OwnerID,
#TransDesc = #TransDescOut OUTPUT
SET #TransDescription = #TransDescOut
Then I use #TransDescription as a value for inserting into column data.
The helper code is:
CREATE PROCEDURE [dbo].[sp_KF_Helpers_CreateInvTransDescription]
( #TransactionTypeID int,
#UserName nvarchar(256),
#OwnerTypeID int,
#OwnerID int,
#TransDesc varchar(256) OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;
declare #rslt int = 0
declare #strTyepID varchar(256) = #TransactionTypeID
declare #strOwnerID varchar(256) = #OwnerID
declare #intOwnerTypeID int = #OwnerTypeID
declare #OwnerStr varchar(256) = 'KF_'
declare #OwnerIDStr varchar(256) = (select Description from KF_OwnerType where ID = #intOwnerTypeID)
select #OwnerStr = #OwnerStr + #OwnerIDStr
declare #sql1 nvarchar(4000)
Select #sql1 = 'Select Top 1 (a.Description + '' - '' + ' + #OwnerStr + '.Name) TransDesc
from KF_InventoryTransactionType a, KF_OwnerType c, ' + #OwnerStr + '
where a.ID = ' + #strTyepID + ' and '
+ #OwnerStr + '.ID = ' + #strOwnerID
exec SP_EXECUTESQL #sql1, N'#TransDesc varchar output ', #TransDesc output
End
As you can see, I am using dynamic SQL to generate the description. The problem is that the help code generates the correct description, but does not pass it back as output.
Anyone know why or where I am losing scope for returning my output description?
You forgot to assign the variable. Try:
select top 1 #TransDesc = a.Description + '' - '' + ' + #OwnerStr + '.Name
...
Also, change the part where you are declaring the parameter of the dynamic script (#TransDesc), or you will run into another issue. Currently the parameter is being declared like this:
#TransDesc varchar output
which is equivalent to
#TransDesc varchar(1) output
Most likely, it should be
#TransDesc varchar(256) output
instead.