Using sql:variable in an insert statement
I'm writing an insert statement for a table with an XML column. Most of the XML is static, but I need to replace the value of an element with the value of a T-SQL variable, as shown here:
CREATE TABLE [dbo].[OrderDetail](
[OrderID] [int] NULL,
[OrderDetail] [xml] NULL
GO
DECLARE @XMLData XML;
DECLARE @ItemID INT;
SET @ItemID = 1000;
SELECT @XMLData = N'
<OrderDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</OrderDetail>
SET @XMLData.modify('insert <ItemID>[sql:variable("@ItemID")]</ItemID> into (/OrderDetail)[1]')
INSERT INTO [dbo].[OrderDetail] ([OrderID], [OrderDetail])
VALUES (@ItemID, @XMLData);
When I run this, it inserts "[sql:variable("@ItemID")]" instead of the value of @ItemID. If someone could show me the proper syntax, I would really appreciate it. Thanks.
Yes, that worked. Now I want to change it a little. I also have an attribute that I need to update with the value of a variable.
DECLARE @XMLData XML;
DECLARE @SetID INT;
DECLARE @SetIDStr VARCHAR(12);
DECLARE @SetIDXML XML;
SET @SetID = 9999;
SET @SetIDStr = CONVERT(VARCHAR(12), @SetID);
SET @SetIDXML = CONVERT(XML, @SetIDStr);
SELECT @XMLData = N'
<OrderDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ItemID>1000</ItemID>
<RightOperand ID="15524" Name="ItemName" Value="15524" />
</OrderDetail>
SET @XMLData.modify('replace value of (/OrderDetail/RightOperand/@ID)[1] with sql:variable("@SetIDXML")');
INSERT INTO [dbo].[OrderDetail] ([OrderID], [OrderDetail])
VALUES (@SetID, @XMLData);
SELECT * FROM [dbo].[OrderDetail];
I'm trying to replace "ID="15524"" with the value of @SetID. This code throws an exception:
Msg 9342, Level 16, State 1, Line 23
XQuery [modify()]: An XML instance is only supported as the direct source of an insert using sql:column/sql:variable.
Thanks again for your help.
Similar Messages
-
How to use sql variables in jdbc send adapter??
Hi,
i wanna use a variable in the sql statement in the jdbc send adapter.
i know i can key sql statement in the "Query SQL Statement" in the jdbc send adapter.but i dont know how to use variables in the sql statement.
i mean, for example, the sql statement is "SELECT * FROM t_student WHERE READFLAG = 0", but now i wanna instead of "0"(the value of the READFLAG) using a variable.
and if i can use a variable to replace the "0"(the value of the READFLAG above sql statement), then how can i send a value to the variable??
request help in the regard.
thx in advance.
BrianHi,
Use the place holders to pass the data at runtime. Check the below structure for more details.
Hope this helps.
Thanks and Regards,
Kalpesh
<root>
<stmt>
<Student action="SQL_QUERY">
<access> SELECT * FROM t_student WHERE READFLAG = '$FLAG$ </access>
<key>
<FLAG>0</FLAG>
</key>
</Student>
</stmt>
</root> -
Use of case in an insert statement...
Hi ,
i have an insert statement in a db packaged procedure which needs a case statement to be used.....
I want to use the case in a statement like the following...
insert into x(a,b,c,d,e)
values(a,b,case b='1' then c_val , d_val , null else null , null , e_val);
In other words when the b_value (b column) has value '1' (in the example above) then the values for c , d columns of the tables are those passed as parameters to the procedure . On the other hand , when the the b_value (b column) has not value '1' then the values for c , d columns of the tables should be null and the on the e column another value passed as parameter to the procedure....????
Is the above general syntax of insert correct...????
Many thanks,
SimonSomething like this could do the trick:
insert into x
(a, b, c, d, e)
values (a,
b,
case
when b = '1'
then c_val
end,
case
when b = '1'
then d_val
end,
case
when b = '1'
then null
else e_val
end
); -
How to use bind variable in this select statement
Hi,
I have created this procedure where table name and fieldname is variable as they vary, therefore i passed them as parameter. This procedure will trim leading (.) if first five char is '.THE''. The procedure performs the required task. I want to make select statement with bind variable is there any possibility to use a bind variable in this select statement.
the procedure is given below:
create or replace procedure test(tablename in varchar2, fieldname IN varchar2)
authid current_user
is
type poicurtype is ref cursor;
poi_cur poicurtype;
sqlst varchar2(250);
THEVALUE NUMBER;
begin
sqlst:='SELECT EMPNO FROM '||TABLENAME||' WHERE SUBSTR('||FIELDNAME||',1,5)=''.THE ''';
DBMS_OUTPUT.PUT_LINE(SQLST);
OPEN POI_CUR FOR SQLST ;
LOOP
FETCH POI_CUR INTO THEVALUE;
EXIT WHEN POI_CUR%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(THEVALUE);
SQLST:='UPDATE '||TABLENAME|| ' SET '||FIELDNAME||'=LTRIM('||FIELDNAME||',''.'')';
SQLST:=SQLST|| ' WHERE EMPNO=:X';
DBMS_OUTPUT.PUT_LINE(SQLST);
EXECUTE IMMEDIATE SQLST USING THEVALUE;
END LOOP;
COMMIT;
END TEST;
Best Regards,So you want to amend each row individually? Is there some reason you're trying to make this procedure run as slow as possible?
create or replace procedure test (tablename in varchar2, fieldname in varchar2)
authid current_user
is
sqlst varchar2 (250);
thevalue number := 1234;
begin
sqlst := 'update ' || tablename || ' set ' || fieldname || '= ltrim(' || fieldname || ',''.'') where substr(' || fieldname
|| ',1,5) = ''.THE ''';
dbms_output.put_line (sqlst);
execute immediate sqlst;
end test;will update every row that satisfies the criteria in a single statement. If there are 10 rows that start with '.THE ' then it will update 10 rows. -
How to use the structure on my insert statement.
I have a function and returning a structure:
<CFSET stLoc_and_AttIDs=StructNew(1)>
<CFSET
stLoc_and_AttIDs["LocID"]="#getLocID.LocationID#">
<CFSET
stLoc_and_AttIDs["AttID"]="#getLocID.AttachmentID#">
I call this function like this:
<CFSET LocAndAttIDs= MyFunction(LocName)>
I'm having difficulty in refering to the values of this
structure in my insert statement:
I'm doing it this way and got error, I'm sure I didn't do it
right, please help.
Insert Into MyTable (Column1, Column2, Column3, .....)
VALUES (#LocAndAttIDs.stLoc_and_AttIDs["LocID"]="#,
#LocAndAttIDs.stLoc_and_AttIDs["AttID"], 23)is that the actual code? if so, it looks like your # aren't
matched up properly. for example, i count 3. there should be an
even number :)
you don't seem to have a closing # after the 2nd variable,
and the closing # for the first variable seems to be a little....
late. it should be after the closing bracket ( ] ), since that's
where the variable name ends. -
Using toUpperCase variable in an If Statement
Hi all,
I am monitoring a user's input in my command-line program, and by converting their input to upper case, I can easily check whether they've input the correct string. However when I use the String in an If statement, it doesn't like it. Here's the simple test code I've been using: public static void main(String[] args) {
BufferedReader keyboardInput = new BufferedReader(new InputStreamReader(System.in));
String priceOfPlayers = null;
try {
System.out.print("Price Of Players: ");
priceOfPlayers = keyboardInput.readLine();
priceOfPlayers = priceOfPlayers.toUpperCase();
System.out.println(priceOfPlayers);
if (priceOfPlayers != "ORIGINAL PRICE" && priceOfPlayers != "CURRENT PRICE") {
System.err.println("\nYou Have Entered An Invalid Option!\n");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}However if I type in say 'original price' or 'current price' or 'ORIGINAL PRICE', it still brings up the error message that I have written! I do not understand why it doesn't interpret the String value properly.
Any help explaining this would be superb!
thanksHi
String comparison should use the equals method instead of ==
if (!priceOfPlayers.equals("ORIGINAL PRICE") && !priceOfPlayers .equals("CURRENT RICE")) {
System.err.println("\nYou Have Entered An Invalid Option!\n");
} -
SQL Performance Analyzer - no insert statements possible ?
Hi together
I traced a insert-stament on 9i, made a tuning set on the 11g for run in 10g. The creation of the tunig set was succesful. But if i want to play the tuning set on 10g with same data i get an error :
Type of SQL Statement not supported !
Can i only trace the select ? Have you made a test with bind variables ?
Thanks for your input.user626582 wrote:
Double postingHa ha , I was going to mention exactly the same!
Aman.... -
Cannot use sqlplus variable in create sequence statement
Hello!
I would like to create a sequence object starting with a number retrieved from a select statement:
var max_resp_no number;
begin
select max(substr(resp_no,2)) into :max_resp_no from brc_mast
where substr(resp_no,1,1)='Z';
end;
print max_resp_no;
drop sequence p659_resp;
create sequence p659_resp start with :max_resp_no;
It tells me that :max_resp_no is an 'invalid number';
TIA,
habeebYou need to do this entirely in PL/SQL. You can either create a procedure, or use an anonymous block. The procedure version is below. Just change the CREATE to a DECLARE to get an anonymous block.
CREATE OR REPLACE PROCEDURE new_seq IS
max_resp_no NUMBER;
BEGIN
SELECT to_number(MAX(SUBSTR(resp_no,2)))
INTO max_resp_no
FROM brc_mast
WHERE SUBSTR(resp_no,1,1)='Z';
EXECUTE IMMEDIATE 'DROP SEQUENCE p659_resp';
EXECUTE IMMEDIATE 'CREATE SEQUENCE p659_resp START WITH '|| max_resp_no;
END;
SQL> CREATE SEQUENCE p659_resp START WITH 1;
Sequence created.
SQL> SELECT p659_resp.nextval from dual;
NEXTVAL
1
SQL> SELECT * FROM brc_mast;
RESP_
Z001
Z002
Z003
Z075
SQL> exec new_seq;
PL/SQL procedure successfully completed.
SQL> select p659_resp.nextval from dual;
NEXTVAL
75Note that the user creating this procedure will need to have CREATE SEQUENCE granted explicitly for the procedure to work. The anonymous block version should work if CREATE SEQUENCE is granted through a role.
John -
Issue using SQL stored procedure to insert/update
With help I finally managed to execute the stored procedure to insert/ update the sql database with the below stored procedure
ALTER PROCEDURE [dbo].[uspInsertorUpdate]
@dp char(32),
@dv char(32),
@e_num char(12),
@mail varchar(50),
@emerg char(32),
@opt1 char(16),
@stat char(20),
@e_id char(35),
@e_tit varchar(64),
@e_date datetime
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM [dbo].[sampleemployee] WHERE e_id= @e_id)
BEGIN
UPDATE [dbo].[sampleemployee]
SET dp = @dp,
dv = @dv,
e_num = @e_num,
mail = @mail,
emerg = @emerg,
opt1 = @opt1,
stat = @stat,
e_tit = @e_tit,
e_date = @e_date
WHERE e_id = @e_id
END
ELSE
BEGIN
INSERT INTO [dbo].[sampleemployee]( dp, dv, e_num, mail, emerg, opt1, stat, e_id, e_tit, e_date)
VALUES ( @dp, @dv, @e_num, @mail, @emerg, @opt1, @stat, @e_id, @e_tit, @e_date );
END
END;
But the issue here is it just insert only one row and update that row only, even if there are some no.of rows need to be inserted . Not sure whyHi Sid_siv,
To pass a table value to stored procedure, you can refer to the sample query below.
create type FileDetailsType as table
FileName varchar(50),
CreatedDate varchar(50),
Size decimal(18,0)
create procedure InsertFileDetails
@FileDetails FileDetailsType readonly
as
insert into
FileDetails (FileName, CreatedDate, Size)
select FileName, CreatedDate, Size
from
@FileDetails;
Reference
http://www.codeproject.com/Articles/22392/SQL-Server-Table-Valued-Parameters
http://forum.codecall.net/topic/75547-sql-server-2008-passing-table-parameter-to-stored-procedure/
Regards,
Charlie Liao
TechNet Community Support -
Using javascript variable in spry if statement
is it possible to put a javascript variable in to the spry if
statement to test?
like <div spry:if="javascriptvar == {ds_RowNumber}"....
thanks.Hi rogerfreak,
When the region processes a spry:if, it simply takes the
value of the spry:if attribute, replaces all of the data references
in it with real values from the data set and then evals the result
(executes the string).
So you can do something like:
<script>
var ds1 = new Spry.Data.XMLDataSet("foo.xml", "/foo/bar");
var gMode = 5;
function GetMode()
return gMode;
</script>
<div spry:region="ds1">
<ul spry:if="gMode == 5">
<li spry:repeat="ds1">{name}</li>
</ul>
<div spry:if="gMode == 12" spry:repeatchildren="ds1">
{name}
</div>
</div>
In the example above the list markup will be written out if
gMode is 5, but if it is 12, it will write out the div markup.
You can also call functions:
<div spry:region="ds1">
<ul spry:if="GetMode() == 5">
<li spry:repeat="ds1">{name}</li>
</ul>
<div spry:if="GetMode()== 12"
spry:repeatchildren="ds1">
{name}
</div>
</div>
--== Kin ==-- -
Using bind variables (in & out) with dynamic sql
I got a table that holds pl/sql code snippets to do validations on a set of data. what the code basically does is receiving a ID and returning a number of errors found.
To execute the code I use dynamic sql with two bind variables.
When the codes consists of a simpel query, it works like a charm, for example with this code:
BEGIN
SELECT COUNT (1)
INTO :1
FROM articles atl
WHERE ATL.CSE_ID = :2 AND cgp_id IS NULL;
END;however when I get to some more complex validations that need to do calculations or execute multiple queries, I'm running into trouble.
I've boiled the problem down into this:
DECLARE
counter NUMBER;
my_id NUMBER := 61;
BEGIN
EXECUTE IMMEDIATE ('
declare
some_var number;
begin
select 1 into some_var from dual
where :2 = 61;
:1 := :2;
end;
USING OUT counter, IN my_id;
DBMS_OUTPUT.put_line (counter || '-' || my_id);
END;this code doesn't really make any sense, but it's just to show you what the problem is. When I execute this code, I get the error
ORA-6537 OUT bind variable bound to an IN position
The error doesn't seem to make sense, :2 is the only IN bind variable, and it's only used in a where clause.
As soon as I remove that where clause , the code will work again (giving me 61-61, in case you liked to know).
Any idea whats going wrong? Am I just using the bind variables in a way you're not supposed to use them?
I'm using Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bitCorrection. With execute immediate binding is by position, but binds do not need to be repeated. So my statement above is incorrect..
You need to bind it once only - but bind by position. And the bind must match how the bind variable is used.
If the bind variable never assigns a value in the code, bind as IN.
If the bind variable assigns a value in the code, bind as OUT.
If the bind variable assigns a value and is used a variable in any other statement in the code, bind as IN OUT.
E.g.
SQL> create or replace procedure FooProc is
2 cnt number;
3 id number := 61;
4 begin
5 execute immediate
6 'declare
7 n number;
8 begin
9 select
10 1 into n
11 from dual
12 where :var1 = 61; --// var1 is used as IN
13
14 :var2 := n * :var1; --// var2 is used as OUT and var1 as IN
15 :var2 := -1 * :var2; --// var2 is used as OUT and IN
16 end;
17 '
18 using
19 in out id, in out cnt; --// must reflect usage above
20
21 DBMS_OUTPUT.put_line ( 'cnt='||cnt || ' id=' || id);
22 end;
23 /
Procedure created.
SQL>
SQL> exec FooProc
cnt=-61 id=61
PL/SQL procedure successfully completed.
SQL> -
Use of the "updlock" hint with update and insert statements
I have inherited some stored procedures and am trying to figure out why the developers decided to use the "updlock" hint on many of the update and insert statements. I have looked around everywhere and have found only one explanation of why "update...with
(updlock)" can be useful, namely when a table has no clustered index:
http://www.sqlnotes.info/2012/10/10/update-with-updlock/ I have found nothing yet that mentions why "insert into...with (updlock)" might be used. I understand why the hint
might be useful on select statements in some cases, but if all of the tables have clustered indexes, is there any good reason to use it on update and insert statements?
Thanks,
Ron
Ron RiceThis form of deadlock error can occur on a table which has a clustered index.
If you are doing updates on a table which has a clustered index and that table also has a nonclustered index and the nonclustered index is used to find the row to update you can see this type of deadlock. For example create a table with a clustered
primary key index and a nonclustered index by running
Create Table Foo(PK int primary key identity, OtherKey varchar(10), OtherData int);
go
Insert Foo Default Values;
go 10000
Update Foo Set OtherKey = 'C' + Cast(PK As varchar(10))
Create Unique Index FooIdx On Foo(OtherKey);
That creates a table with 10000 rows, a clustered index and a nonclustered index. Then run
Begin Transaction
Update Foo Set OtherData = 1 Where OtherKey = 'C5'
That will use the FooIdx index to find the row that needs to be updated. It will get a U lock on the index row in the FooIdx index, then an X lock on the row in the clustered index, update that row, then free the U lock on FooIdx, but keep the X lock
on the row in the clustered index. (There is other locking going on, but to simplify things, I'm only showing the locks that lead to the deadlock).
Then in another window, run
Begin Transaction
Update Foo Set OtherData = 2 Where OtherKey = 'C5'
This will get a U lock on the index row in the FooIdx index, then try to get an X lock on the row in the clustered index. But that row is already exclusively locked, so this second window will wait holding a U lock on FooIdx row and is waiting for
an X lock on the clustered index row.
Now go back to the first window and run
Update Foo Set OtherData = 3 Where OtherKey = 'C5'
This will once again try to get the U lock on the FooIdx row, but it is blocked by the U lock the second window holds. Of course the second window is blocked by the X lock on the clustered index row and you have a deadlock.
All that said, I certainly do not routinely code my updates with UPDLOCK. I try to design databases and write code so that deadlocks will be rare without holding excessive locks. The more locks you hold and the longer you hold them, the more
blocking you will get and the slower your system will run. So I write code that if a deadlock exception occurs, it is properly handled. Then if too many deadlocks occur, that is the time to go back to the code to see what changes are needed to
decrease the number of deadlocks (one way to do that may be to get locks earlier and/or hold them longer.
But I wouldn't worry much about this form of deadlock. It is, in my experience, vary rare. I don't recall ever seeing it in a production environment.
Tom -
[php+mysql] how to use variables in a select statement?
Hi all,
I'm searching for a way to use a variable in the select
statement of mysql
query.
I have this variable that can contain:
$var=field_1 field_2 field5
or
$var=field3 field4 field8
so, the variable content is not always the same.
I would like to filter a table selecting only the columns
specified by the
current $var content.
Is this possible to do something like this?
$var=field1 field5 field10
SELECT string_to_array($var)
FROM mytable
ORDER BY mysortfield ASC
Or, is there another way to select columns dynamically?
Thanks for any suggestion.
tonyHi all,
I'm searching for a way to use a variable in the select
statement of mysql
query.
I have this variable that can contain:
$var=field_1 field_2 field5
or
$var=field3 field4 field8
so, the variable content is not always the same.
I would like to filter a table selecting only the columns
specified by the
current $var content.
Is this possible to do something like this?
$var=field1 field5 field10
SELECT string_to_array($var)
FROM mytable
ORDER BY mysortfield ASC
Or, is there another way to select columns dynamically?
Thanks for any suggestion.
tony -
Using Presentation variables..along with case statements..
Hi All.
I have a issue using presentation variable along with CASE statements. My approach is
1) I have a dashboard prompt, which is being set as Presentation variable.
Based on the value selected in prompt, for ex the values of prompt can be 'ABC' and 'DEF'.
I have a calculated column, the calculation goes this way...
The forumal is
CASE WHEN @{Presentation Variable Name} = 'ABC' THEN xxxxxxxxxx ELSE IF @{Presentation Variable Name} = 'DEF' END. It gives error of "no table being referenced"..
Is this is the right approach??
Can i get the values of variable in a column formula, so that a column can have values selected in prompt?
Can anybody pls help me here..
Thanks in advance...Hi
Thanks for the quick response..
I agree to ur point..
But the requirement is
Based on the value of the prompt I need to switch the calculation in one of the formula area of one column..
If Prompt value is ABC then one kind of calculation in Fx and If the prompt value is DEF then one kind of calculation in the same Fx..
How can I acheive this?
Thanks in advance.. -
EXEC SQL Error: ORA-01401: Inserted value too large for column
Getting this SQL Error: ORA-01401: Inserted value too large for column..on an EXEC SQL Insert statement when writing to an
external Oracle DB from SAP.
On further analysis..it appears that this happens to the fields..when the string length matches the field length.
Example: Plant field is defined as char(4) on the SAP side and it is a Varchar2(4) on the Oracle side.
When a value like '1015' is passed thru a variable in the insert statement then this ORA-01401 error pops up.
No error:
- if the value '1015' is passed directly in the insert statement to the external table (or)
- when a value with 3 chars or less(like the first three chars..101) is passed thru a variable defined as 'Plant(4) type c'.
- when using EXEC sql within SAP
- when reading from the external db table
This was working ok until the Oracle Patch P9147110 was installed recently.
Any suggestions !Hello Dvas,
what's the characterset of your external database?
What's the column definition in your external database (byte or character based)?
If you use a characeterset like UTF8 it is possible, that one character needs more than one byte and then you will run into such kind of issues if the definition is too small.
Regards
Stefan
Maybe you are looking for
-
Google Earth and Google Desktop on iMac
Earth works great. Do I wanna bother with Desktop?
-
Payment Advice created in CM doesnt flow to Liquidy Planner.
Hello, I am using Cash Management and Liquidity Planner. In Liquidity Planner I have to build Cash Flow to see Forecast and Actual data. I am using FF63 to post Payment Advices in Cash Management. I would like to see this document posted in Cash Mana
-
Dear All, I am learning XI and picking up quickly. I have couple question in XI.I know the question which are raised are very basic and please bare me. I would be glad and will be awarded points for good explanation for the below questions, 1. fo
-
The opportunity to re-start in Firefox is not even activated
-
Help! need help w/ terminal...
my friend borrowed my computer to try and rip videos from their ipod to my computer then move them to another ipod...anyway, she typed something in terminal and now i have a "network", "servers", ".DS_Store" icons on my desktop and seemingly everywhe