I am really in a great trouble. My requirement is quite complex, as I feel, it may be quite simple for some of you. Here is my problem - Actually I am doing a project, where client has a specific requirement. i.e. he want's to build a query on runtime for selecting particular record he wants, so that we have provided a user interface where he can select any datasource e.g. SQL, Oracle, Excel etc. He also specifies the database name. He is displayed all the tables and columns under those tables. He selects columns from those table boxes and write the query he wants, with where clause, if required. I am saving these query in a table, storing column names in another table where we map those oringinal column names with columns of another table, wehre we want to store actual result set of the prepared query by the user. for examaple .. if user preapare query like - 'SELECT CUST_ID, CUST_NAME FROM CUSTOMER WHERE CUST_ID = 10' In case of above query I will store CUST_ID in column COL1 of table TAB1 and CUST_NAME in COL2 of table TAB1, like that we have such fifty columns in that table. Now question is here every thing is dynamic data provider, database, tables, columns and where clause, then how can get the result set out of those queries and store that query output in the that storage table with columns col1, col2 and so on, upto 50 columns. Please help me on this, as it is so urgent. I will be very much thankful to you people.
Hi, I'm having an SSIS package which gives the following error when executed :
Error: 0xC002F210 at Create Linked Server, Execute SQL Task: Executing the query "exec (?)" failed with the following error: "Syntax error or access violation". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.Task failed: Create Linked Server
The package has a single Execute SQL task with the properties listed below :
General Properties Result Set : None
ConnectionType : OLEDB Connection : Connected to a Local Database (DB1) SQLSourceType : Direct Input SQL Statement : exec(?) IsQueryStorePro : False BypassPrepare : False
Parameter Mapping Properties
variableName Direction DataType ParameterName
User::AddLinkSql Input Varchar 0
'AddLinkSql' is a global variable of package scope of type string with the value Exec sp_AddLinkedServer 'Srv1','','SQLOLEDB.1',@DataSrc='localhost',@catalog ='DB1'
When I try to execute the Query task, it fails with the above error. Also, the above the sql statement cannot be parsed and gives error "The query failed to parse. Syntax or access violation"
I would like to add that the above package was migrated from DTS, where it runs without any error, eventhough it gives the same parse error message.
I would appreciate if anybody can help me out of this issue by suggeting where the problem is.
I need to implement a "dynamic" select query, in which I want that the type and the number of columns are variable/changeable. For example using the parameters of a stored procedures. I would have a client code (written in VB .NET) in which I would choose the columns that I want to display in a DataGridView.
How should I modify the SELECT line or the SP in general to solve the problem??
The code I need to modify is this:
Code Snippet CREATE PROCEDURE uspSelect1 @iDataInit datetime = '01 gen 1753', @iDataEnd datetime = '31 dic 9999', @iArticle nvarchar(50) = N'%', @iMachineNum smallint, @iTypeMaterial nvarchar(50) = N'%', @iNominalCount float, @iOperator nvarchar(50) = N'%', @iCustomer varchar(50) = N'%', @iComments nvarchar(1000) = N'%', @iLanguage nvarchar(50) = N'%' AS SELECT i.IDsample, i.Date, i.Article, i.MachineNum, i.TypeMaterial, i.NominalCount, i.Operator, i.Customer, i.Comments, i.Language, r.Um, r.CVm FROM Identification i JOIN Reports r ON (i.IDsample = r.IDsample) WHERE i.Date BETWEEN @iDataInit AND @iDataEnd AND i.Article LIKE @iArticle AND i.MachineNum = ISNULL(@iMachineNum, i.MachineNum) AND i.TypeMaterial LIKE @iTypeMaterial AND i.NominalCount = ISNULL(@iNominalCount, i.NominalCount) AND i.Operator LIKE @iOperator AND i.Customer LIKE @iCustomer AND i.Comments LIKE @iComments AND i.Language LIKE @iLanguage ORDER BY i.IDsample
declare @AccountID numeric(3,0) set @AccountID = 101 select * from AccountTest WHERE AccountID IN (CASE WHEN @AccountID = 101 THEN (100,101) ELSE @AccountID END)
I m getting error like
Msg 102, Level 15, State 1, Line 9 Incorrect syntax near ','.
Hi all my problem is as follows : when i try to configure an ODBC DataAdapter using the configuration wizard
i use the query builder to select some fields from multiple tables , the displayed info depends in a user input , when i define the input parameter by writing(= ?) in the criteria column of the input field and continues , it displays an error
Error H4000 Error while executing the query , Error near ')' near character (214 for example).
so please if any one knows the solution to this error reply soon
I was having some errors from the webpage accessing the OLlinks table in the database. Error executing non query: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader() at admin_admOLEditLinks.selectData(String strID) in e:wwwroothomeadminadmOLEditLinks.aspx.cs:line 101DateTime:5/23/2007 1:14:10 PMSource:http://www.myDomain.comiAdmin/admOLEditLinks.aspx?ID=3ErrorMessage:Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. I kept getting the above error so then I try to access the table directly inside of MS SQL Server Management Studio and then I recieved the following error: SQL Execution Error. Executed SQL statement: SELECT lnkID, linkFromID, linkToID FROM OLlinks Error Source: .Net SqlClient Data Provider Error Message: Timeout expired. The timeout period elapsed prior to completion of the opration or the server is not responding.
Open any other table works fine except this table only. Any help is much appreciated.
Hi, I have written a stored proc to bulk insert the data from a data file. I have a requirement that i need to insert the data into a table of which the name is not known. I mean to say that the table name will be passed as a parameter to the stored proc. And also i need to insert the date that will also be passed as the parameter to the stored proc
The follwing statement works fine if i give the table name directly in the query
Code Snippet
DECLARE @LastUpdate varchar(20)
SET @LastUpdate = 'Dec 11 2007 1:20AM'
INSERT INTO Category SELECT MSISDN, @LastUpdate FROM OPENROWSET( BULK '\remotemachinedatafile.txt', FORMATFILE = '\remotemachineFormatFile.fmt', FIRSTROW = 2) AS a
To satisfy my requirement ( i.e passing the table name dynamically , and the date) , i have formed the query string ( exact one as above ) and passing it to EXEC statement. But its failing as explained below
Code Snippet
@Category - Will be passed as a parameter to the stored proc
Print @vsBulkSQL - This prints the folliwing statement
INSERT INTO Category SELECT MSISDN, 'Dec 11 2007 1:20AM' FROM OPENROWSET ( BULK '\remotemachineDataFile.txt' , FORMATFILE ='\remotemachineFormatFile.fmt', FIRSTROW =2) AS a
Exec @vsBulkSQL - This statement gives the following error
The name 'INSERT INTO Sports SELECT MSISDN, 'Dec 11 2007 1:20AM' FROM OPENROWSET ( BULK '\remotemachineSecond.txt' , FORMATFILE ='\remotemachineFormatFile.fmt', FIRSTROW =2) AS a' is not a valid identifier.
Can any one please point out where am i doing wrong? Or do i need to do anything else to achive the same
Hi,I have a web application using Stored Procedure (SP). I see that there's a SP taking long time to execute. I try to capture it by Profiler Tool, and find out that with the same SP on the same db with the same parameter. The duration of executing by my web app is far bigger than the duration of executing on SQl server management studio - query windowPlease see the image attached http://kyxao.net/127/ExecutionProblem.png Any ideas for this issue?Thanks a lot Jalijack
I am facing a problem in a dynamic sql query. My query is
EXEC (' SELECT A.Atm_Model, CU.Credit_Union_Name, CASE WHEN LICENSED_SERVICES_NAME=''VISA'' THEN 1 ELSE 0 END AS "VISA", CASE WHEN LICENSED_SERVICES_NAME=''PLUS'' THEN 1 ELSE 0 END AS "PLUS", A.Atm_Make FROM ATM A LEFT JOIN Credit_Union CU ON CU.Credit_Union_ID=A.Credit_Union_ID LEFT JOIN Credit_Union_Licensed_Services CULS ON CU.Credit_Union_ID=CULS.Credit_Union_ID LEFT JOIN Licensed_Services LS ON LS.Licensed_Services_ID=CULS.Licensed_Services_ID ')
when i execute this query it works fine but when i try to execute the following query
SET @VAR=dbo.DYN() SET @VAR1=('SELECT A.Atm_Model, CU.Credit_Union_Name, '+@VAR+' A.Atm_Make FROM ATM A LEFT JOIN Credit_Union CU ON CU.Credit_Union_ID=A.Credit_Union_ID LEFT JOIN Credit_Union_Licensed_Services CULS ON CU.Credit_Union_ID=CULS.Credit_Union_ID LEFT JOIN Licensed_Services LS ON LS.Licensed_Services_ID=CULS.Licensed_Services_ID') EXEC (@VAR1)
it throws an error that "Incorrect syntax near VISA"
dbo.DYN is a function that writes string CASE WHEN LICENSED_SERVICES_NAME=''VISA'' THEN 1 ELSE 0 END AS "VISA",
CASE WHEN LICENSED_SERVICES_NAME=''PLUS'' THEN 1 ELSE 0 END AS "PLUS",
I want to capture an error through dynamic query. I have got a link server. I will execute a procedure in database a which will insert data into a table of database b. If while inserting into the table if database b generates an error I have to catch that error in database a and show it. Please help.
Hi ,What i exacly want to do is1. Connect to OLAP server from my Sql server using following querystring'SELECT a.* FROMOpenRowset(''MSOLAP'',''DATASOURCE="RAPID-CHRISTUS"; InitialCatalog="MRS";2. I want to execute my dynamically created MDX query . This query canbe greater than 8000 varchar limit.When my query length exceeds 8000 length i break it up into 2 parts..Here I have broken my query into 2 parts@mdx1 and @mdx2Now i execute the entire statement asexec('SELECT a.* FROMOpenRowset(''MSOLAP'',''DATASOURCE="RAPID-CHRISTUS"; InitialCatalog="MRS";'',' + @mdx1 + mdx2 ') as ' )Still error comes that :Unclosed quotation mark before the character string 'WITH MEMBER ..('With member' is the starting statement of my MDX query)Is there any other way to connect to OLAP server and execute an MDXstatement with a Length greater than 8000 charsTIA
Hi, In a stored procedure (SP1) I call another stored procedure (SP2), passing along parameters. In SP2 I dynamically build cursor c1. I can execute SP2 without any problems but when I start SP1 I get the following message:
Msg 16916, Level 16, State 1, Procedure SP2, Line 114 A cursor with the name 'C1' does not exist.
Yes, the cursor is of type GLOBAL. I am sure I miss something here ... Any help is highly appreciated !
I have created a trigger on a table that get's too many updates so to analyze what records and what columns get updates I have coded a trigger that inserts into a table the record key and a flag on each column to let me know what is updates. Now that I am presenting the data to the developers I have been asked to provide the update / insert or delete statement
So on my trigger I have tried using dynamic management views but its returning the actual trigger code not the parent SQL Script that triggered it.
This is what I am using.
select@dDate as dDate, dest.[dbid], dest.[objectid], dest.[number], dest.[encrypted], case when sder.[statement_start_offset] > 0 --the start of the active command is not at the beginning of the full command text thencasesder.[statement_end_offset]
Hello All!! Below is a part of my code. I need to find out if I could execute the below statement.
select @string_sortorder = 'select max(sortorder) from geo_lineobj where pipeid = ' + str(@geo_pipeid) select @string_sortorder exec @string_sortorder @max_sortorder
When I select the @max_sortorder the value I'm getting is a null. The sortorder is an int datatype and the @geo_pipeid is also an int datatype. I need to to get the @max_sortorder to continue my coding. Does anyone know why I'm getting a null @max_sortorder?
Hello, I have a problem with a SELECT Query in SQL SERVER 2000. Here the code :SELECT Produits.PDT_ID_PRODUIT, Produits.PDT_NOM, Categories.TYP_NOM + ' .::. ' + Produits.PDT_NOM AS nomvin FROM Categories INNER JOIN Produits ON Categories.TYP_ID_CAT = Produits.PDT_CODE_CAT WHERE(((Produits.PDT_READY) = 1)) ORDER BY Produits.PDT_NOMThe text error is :Exception Details: System.Data.SqlClient.SqlException: Cannot resolve collation conflict for column 3 in SELECT statement.The 3 column is "Categories.TYP_NOM + ' .::. ' + Produits.PDT_NOM AS nomvin". This query where good several weeks and now is not... I don't understand. What is the error ?
case when (r.creditdate >= dateAdd(m, -3, convert(datetime,convert(varchar(10), getdate(), 112), 112)) AND r.creditdate < dateAdd(d, 1, convert(datetime,convert(varchar(10), getdate(), 112), 112))) then r.creditnumber else replace(r.creditnumber,substring(r.creditnumber,1,len(r.creditnumber)-4),'xxxx xxxx xxxx ') end as creditcard from creditcardtable r
join salestable s
on s.salesdate = r.creditdate
where (r.creditnumber <> '') AND (NOT (ISNULL(r.creditnumber, '999') = '999'))
order by r.creditdate desc
first time i execute this query i got an error like: An error occurred while executing batch. Error message is: Internal connection fatal error.
second time i execute this query i got an error like: An error occurred while executing batch. Error message is: Non-negative number required. Parameter name: count
can anyone tell me what's the reason? and any solution for it?
I have multiple SqlDataSources on a page. I only want them to execute the select query when the user performs a certain action. Is this possible? Or do they all execute as soon as the page is loaded?
VIEW behaviour depending on what operation is run on it.
VIEW syntax is CREATE VIEW xx AS SELECT ... It would be very convinient to know wether a select, update, insert or delete is the operation executed on it so the view could take action accordingly, ie CREATE VIEW xxx AS SELECT .. CASE UPDATE THEN do_this CASE SELECT THEN do_that etc. Does anyone know if this is possible?
Got this error running a query with ssms2014 on SqlServer2014 but db has Compatibiliy level 100 (sql2008)
no sql error code in message and no error found in eventviewr (sqlserver log, windows log, application log ecc)when i run that query i got this message in "messages" tab, and in results tab i got a strange result, indeed the value returned doesn't exists in table.
ex table1.field1 possible values= 2,3 it returns 1113344
we got that error thru jdbc too...that query use a lot of joins, unfortunatley i can't post it here. today got this error, so i make a copy of 1 of involved table into another db in the same instance, re run the query on the original db, and it works well.
Hi I have a problem executing a SELECT inside a TRAN against other computer
For example: IN THE SQL Query Analizer of the COMPUTER2 1) this runs OK BEGIN TRAN SELECT * FROM COMPUTER2.DATABASE.DBO.TABLE COMMIT TRAN 2) this runs OK SELECT * FROM COMPUTER2.DATABASE.DBO.TABLE 3) this runs OK SELECT * FROM COMPUTER1.DATABASE.DBO.TABLE 4) this runs bad BEGIN TRAN SELECT * FROM COMPUTER1.DATABASE.DBO.TABLE COMMIT TRAN
The problem is that TABLE locks and it does not finish.
I've been looking for similar ERRORS in Microsoft Support but I found nothing I've uninstall and install de SQL server 2000 SP4 and the problems continues the same
I hope I'm posting this in the correct forum. If not I apologize. I have a nested select query that I imported from Oracle:
Oracle Version:
Code Snippetselect avg(days) as days from ( select dm_number, max(dm_closedate) - max(comment_closed_date) as days from dm_data where dm_type = 'prime' and dm_closedate <= '31-dec-2007' and dm_closedate >= '1-dec-2007' and program = 'aads' group by dm_number)
SQL Version:
select round(abs(avg(days)), 0) as days from (select dm.dm_number, abs(datediff(DAY,max(dm.dm_closedate), max(dm.comment_closed_date))) as days from dm_data dm, ProgramXref px where px.Program_Name = 'aads' and dm.Program_Id = px.Program_Id and dm.dm_type = 'prime' and dm.dm_closedate <= '31-dec-2007' and dm.dm_closedate >= '1-dec-2007' group by dm.dm_number)
In Oracle the query runs fine. In SQL I am getting a "Line 10: Incorrect syntax near ')'." error. If I run just the nested portion of the query, there are no errors. It only happens when the first query tries to query the nested query. Can anyone help me get the syntax correct?
I am getting this error An error occurred while executing batch. Error message is: The directory name is invalid."
in sql management studio.
i found that if i switch to results to text i don't get the error but with results to grid I get it no matter what i query in any database on the server.
where DATEPART(yyyy, ActivityDate) = DATEPART(yyyy, getdate()) and Month(ActivityDate) = 3
Group By Datepart(yy,Activitydate), Month(ActivityDate), DataCenter, Farm
) A
INNER JOIN
(SELECT *
from Monthly
where Year = DATEPART(yyyy, getdate()) ) B
ON
A.Year = B.Year and
A.Month = B.Month and
A.DataCenter = B.DataCenter and
A.Farm = B.Farm
Above query executes fine giving output as 3519; that too in 1sec. However when i try to apply criteria on Monthly table of Month=3, query just keeps executing for hours..
When I execute this query, I get the error: 'The colum prefix 'ClassifiedAd does not match with a table'. But the table does exist. Does anyone know what's wrong?
select ca.ItemID, ca.ModuleID, 'CreatedByUser' = u1.FirstName + ' ' + u1.LastName, ClassifiedAd.CreatedDate, 'UpdatedByUser' = u2.FirstName + ' ' + u2.LastName, ca.UpdatedDate, ca.AdTitle, ca.AdText, ca.AdHasImage, ca.AdPOCName, ca.AdPOCEmail, ca.AdPOCPhone from ClassifiedAd ca left outer join Users u1 on ca.CreatedByUser = u1.UserID left outer join Users u2 on ca.UpdatedByUser = u2.UserID where ca.ItemID = 1 and ca.ModuleId = 1
Hi everybody, I need a syntax in SQL Server 7.0. By using which I need to excecute a query from file. By using xp_cmdshell I am getting it. But whole results comes in a single column. I need the result set as it appears while executing the query. Can you help me in this. Any help will be appreciated.