How to execute dynamic SQL in .net? - sql-server

I'm trying to write the SQL execute statement below. I'm getting an error in .net saying
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid column name 'Survey'
There is no Survey column which is correct, but what is crazy is that it is getting that value from the #SurveyNumber variable. I think my exec code is correct, but maybe I'm not escaping the #SurveyNumber properly?
The #SurveyNumber variable contains this string "Survey - 1234"
#SurveyNumber varchar(50),
#RefIds varchar(max)
AS
Begin
exec('SELECT
Distinct
r.DRAWING,
r.[DESC],
r.REFMEMO,
r.OP_PSI,
r.MAX_PSI,
r.MAX_TEMP,
r.DESIGN,
r.CORR_RATE,
r.MIN_INSP,
r.INSP_LOC,
r.REPL_DATE,
r.LAST_INSP,
r.NEXT_INSP,
r.ALLOW_PSI,
IIf( r.[CF1] is null Or r.[CF1]='''',''Max'', IIf(r.[CF1]=''L'',''Long'',IIf(r.[CF1]=''S'',''Short'',IIf(r.[CF1]=''U'',''User'',''NA''))))AS CF1,
r.[NF2]*1000 as NF2,
r.CF2,
r.V_Last_Insp,
r.V_Next_Insp,
r.V_Concern,
r.V_Memo,
r.V_Report,
r.V_Interval,
r.Insulated,
r.AVG_NEXT_INSP,
r.AVG_REPL_DATE,
r.Scaffolding,
r.Number_Xrays,
r.MIN_RMS,
r.DRAWING_FLAG
From ref r
where r.SurveyNumber = ('+#SurveyNumber+') and r.Id In ('+#RefIds+')
ORDER BY r.NEXT_INSP asc')
End

Related

Why do I get "Synonym 'syn.Syn_AAA' refers to an invalid object" Error?

When I execute a stroed procedure it works. But specifically when I run the select statement I get the following error
Synonym 'syn.Syn_NEO_DB_tGradeAliases' refers to an invalid object.
SELECT
aa.CompanyId [LegCompanyId],
aa.ProductId AS [LegGradeId],
aa.GradeAliasId [LegGradeAliasId],
aa.ProductName AS [LobGradeText],
aa.[Alias] [GradeAlias],
aa.PhraseKey [PhraseKey],
GETUTCDATE() AS 'TimeStamp'
FROM syn.Syn_AAA aa
I haven't done any database change/permission change.
How can I overcome this?
I ran following query and it shows the base_object_name correctly linked to my table.
SELECT * FROM sys.synonyms WHERE name = 'Syn_AAA'
I overcame by replacing synonym with [LINKED_SERVER].[DB_NAME].[SCHEMA_NAME].[OBJECT_NAME].

How to write a simple stored procedure in advantage data architect

I am creating a WPF application using Advantage database server. I want to insert some data using stored procedure
Any sample code ?
I tried two input parameter TestID and TestName (both NCHAR)
INSERT INTO TestTable(
Test_Id,
Test_Name)
VALUES (
#TestID,
#TestName);
But show error like
Error 7200: AQE Error: State = HY000; NativeError = 5154;
[SAP][Advantage SQL Engine][ASA] Error 5154: Execution of the stored
procedure failed. Procedure Name: TestInsert. Error 7200: AQE
Error: State = S0000; NativeError = 2121; [SAP][Advantage SQL
Engine]Column not found: #TestID -- Location of error in the SQL
statement is: 42 (line: 3 column: 5) Error in stored procedure:
TestInsert AdsCommand query execution failed.
I am new in SAP ADS. Please help me.
use _XXXX notation for input parameters.
ie,
INSERT INTO TestTable( Test_Id, Test_Name)
VALUES ( _#TestID, _#TestName);

Oracle if-else query to check table exist otherwise show a message?

When i am running below query first time its working but after again i am going to run this query i am getting exception
Select count(*) into rec from all_tables where table_name='DefaultTable';
if(rec=1) then
CREATE TABLE DefaultTable(
Code INT NOT NULL,
Code1 INT NOT NULL,
ResultCode INT NOT NULL,
CONSTRAINT DefaultTable_PK PRIMARY KEY(Code,Code1)
);
else
PRMOPT DefaultTable Already Exist //To print in Console
end if;
Can anyone tell what i am doing wrong? and what all i am doing wrong to write the above query ?
Error starting at line 2 in command:
if(rec=1) then
Error report:
Unknown Command
Error starting at line 3 in command:
CREATE TABLE DefaultTable(
Code INT NOT NULL,
Code1 INT NOT NULL,
ResultCode INT NOT NULL,
CONSTRAINT DefaultTable_PK PRIMARY KEY(Code,Code1)
Error at Command Line:3 Column:14
Error report:
SQL Error: ORA-00955: name is already used by an existing object
00955. 00000 - "name is already used by an existing object"
*Cause:
*Action:
Error starting at line 16 in command:
else
Error report:
Unknown Command
Error starting at line 17 in command:
PRMOPT Table Already Exist
Error report:
Unknown Command
Error starting at line 18 in command:
end if
Error report:
Unknown Command
Well, as I understand the author is trying to do it in one sql query. But in Oracle you can not use IF statement in simple sql. Moreover, even if you use PL/SQL the DDL statements are not allowed to be directly invoked from PL/SQL code, so you should use dynamic SQL. I think, the following script will do what you want:
DECLARE
rec NUMBER;
BEGIN
SELECT COUNT(*) INTO rec FROM all_tables WHERE table_name='DEFAULTTABLE';
IF (rec=0) THEN
EXECUTE IMMEDIATE 'CREATE TABLE DefaultTable(
Code INT NOT NULL,
Code1 INT NOT NULL,
ResultCode INT NOT NULL,
CONSTRAINT DefaultTable_PK
PRIMARY KEY(Code,Code1,ResultCode)
)';
ELSE
dbms_output.put_line('DefaultTable Already Exist');
END IF;
END;
Please, note that in order to see the messages printed via dbms_output, you should execute:
SET SERVEROUTPUT ON;
If you read the error message you will notice it says:
ORA-00955: name is already used by an existing object
This means you are trying to create a table that already exists. That explains why it runs the first time and not any more after that.
Check the entries in all_tables and you will find that Oracle creates tablenames in uppercase. So check for 'DEFAULTTABLE'.

Scalar function fn_cdc_get_min_lsn() constantly returns '0x00000000000000000000' for valid table names?

I have Change Data Capture (CDC) activated on my MS SQL 2008 database and use the following code to add a new tabel to the data capture:
EXEC sys.sp_cdc_enable_table
#source_schema ='ordering',
#source_name ='Fields',
#role_name = NULL,
#supports_net_changes = 0;
However, whenever I try to select the changes from the tracking tables using the sys.fn_cdc_get_min_lsn(#TableName) function
SET #Begin_LSN = sys.fn_cdc_get_min_lsn('Fields')
I always get the zero value.
I tried adding the schema name using the following spelling:
SET #Begin_LSN = sys.fn_cdc_get_min_lsn('ordering.Fields')
but this didn't help.
My mystake was to assume that sys.fn_cdc_get_min_lsn() accepts the table name. I was mostly misguided by the examples in MSDN documentation, probably and didn't check the exact meaning of the parameters.
It turns out that the sys.fn_cdc_get_min_lsn() accepts the capture instance name, not table name!
A cursory glance at my current capture instances:
SELECT capture_instance FROM cdc.change_tables
returns the correct parameter name:
ordering_Fields
So, one should use underscore as schema separator, and not the dot notation as it is common in SQL Server.
I know this is mostly already explained in this post but I thought I would put together my evenings journey through CDC
This error:
"An insufficient number of arguments were supplied for the procedure or function cdc..."
Is probably caused by your low LSN being 0x00
This in turn might be because you put the wrong instance name in with fn_cdc_get_min_lsn.
Use SELECT * FROM cdc.change_tables to find it
Lastly make sure you use binary(10) to store your LSN. If you use just varbinary or binary, you will again get 0x00. This is clearly payback for me scoffing at all those noobs using varchar and wondering why their strings are truncated to one character.
Sample script:
declare #S binary(10)
declare #E binary(10)
SET #S = sys.fn_cdc_get_min_lsn('dbo_YourTable')
SET #E = sys.fn_cdc_get_max_lsn()
SELECT #S, #E
SELECT *
FROM [cdc].[fn_cdc_get_net_changes_dbo_issuedToken2]
(
#S,#E,'all'
)
The above answer is correct. Alternatively you can add an additional parameter capture_instance to the cdc enable
EXEC sys.sp_cdc_enable_table
#source_schema ='ordering',
#source_name ='Fields',
#capture_instance = 'dbo_Fields'
#role_name = NULL,
#supports_net_changes = 0;
then use the capture_instance string in the min_lsn function
SET #Begin_LSN = sys.fn_cdc_get_min_lsn('dbo_Fields')
will return the first LSN, and not 0x00000000000000000000.
This is partiularly useful when trying to solve the error
"An insufficient number of arguments were supplied for the procedure or function cdc..." from SQL when calling
cdc_get_net_changes_Fields(#Begin_LSN, sys.fn_cdc_get_max_lsn(), 'all')
Which simply means "LSN out of expected range"

Parsing xml in sql server

I have a table with an ntext type column that holds xml. I have tried to apply many examples of how to pull the value for the company's name from the xml for a particular node, but continue to get a syntax error. Below is what I've done, except substituted my select statement for the actual xml output
DECLARE #companyxml xml
SET #companyxml =
'<Home>
<slideshowImage1>1105</slideshowImage1>
<slideshowImage2>1106</slideshowImage2>
<slideshowImage3>1107</slideshowImage3>
<slideshowImage4>1108</slideshowImage4>
<slideshowImage5>1109</slideshowImage5>
<bottomNavImg1>1155</bottomNavImg1>
<bottomNavImg2>1156</bottomNavImg2>
<bottomNavImg3>1157</bottomNavImg3>
<pageTitle>Acme Capital Management |Homepage</pageTitle>
<metaKeywords><![CDATA[]]></metaKeywords>
<metaDescription><![CDATA[]]></metaDescription>
<companyName>Acme Capital Management</companyName>
<logoImg>1110</logoImg>
<pageHeader></pageHeader>
</Home>'
SELECT c.value ('companyName','varchar(1000)') AS companyname
FROM #companyxml.nodes('/Home') AS c
For some reason, the select c.value statement has a syntax problem that I can't figure out. On hover in SSMS, it says 'cannot find either column "c" or the user-defined function or aggregate "c.value", or the name is ambiguous.'
Any help on the syntax would be greatly appreciated.
try this
DECLARE #companyxml xml
SET #companyxml =
'<Home>
<slideshowImage1>1105</slideshowImage1>
<slideshowImage2>1106</slideshowImage2>
<slideshowImage3>1107</slideshowImage3>
<slideshowImage4>1108</slideshowImage4>
<slideshowImage5>1109</slideshowImage5>
<bottomNavImg1>1155</bottomNavImg1>
<bottomNavImg2>1156</bottomNavImg2>
<bottomNavImg3>1157</bottomNavImg3>
<pageTitle>Acme Capital Management Homepage</pageTitle>
<metaKeywords>CDATA</metaKeywords>
<metaDescription>CDATA</metaDescription>
<companyName>Acme Capital Management</companyName>
<logoImg>1110</logoImg>
<pageHeader></pageHeader>
</Home>'
DECLARE #Result AS varchar(50)
SET #result = #companyxml.value('(/Home/companyName/text())[1]','varchar(50)')
SELECT #result

Resources