I'm just wondering if we can save sql aggregate functions into a variable. I have this query:select company, dept, sum(pers) as pers1, sum(amount) as amount1,sum(amount)/sum(pers) as wage from xxtestsumgroup by company, dept instead of calling sum(amount) and sum(pers) again in "sum(amount)/sum(pers) as wage",I would like to save them in some kinda variable in the select clause so it will save process time.Sorry but im new to sql programming. So thx for your understanding.
how do you store a datareader propety to a variable? Below is my current code. I have already declared my connectionString and sqlComm objects, as well as the userName and such. I need to store the value from the dr to the variables, UserName, UserPass, and serverName. ThanksTry sqlCon.Open() dr = sqlComm.ExecuteReader While dr.Read userName = dr("uName").ToString LogInfo("userName = " & userName)
i'm trying to read an image file from a database(ms-sql, .mdf) with type image. Anyone have any ideas on how to do this? I have a table adapter created but could not assign it to my byte[] variable. Thanks in advance.
insert into #t(branchnumber) values (005) insert into #t(branchnumber) values (090) insert into #t(branchnumber) values (115) insert into #t(branchnumber) values (210) insert into #t(branchnumber) values (216)
[code]....
I have a parameter which should take multiple values into it and pass that to the code that i use. For, this i created a parameter and temporarily for testing i am passing some values into it.Using a dynamic SQL i am converting multiple values into multiple records as rows into another variable (called @QUERY). My question is, how to insert the values from variable into a table (table variable or temp table or CTE).OR Is there any way to parse the multiple values into a table. like if we pass multiple values into a parameter. those should go into a table as rows.
I have a set of .dtsx files that connect to an Oracle database. The Oracle username and pw values are saved in variables set up in the .dtsx files. These two variables do not have expressions, rather, these two variables feed other variables and their expressions.Theses files are now moving from one environment to another and the Oracle username and pw must be updated to connect to the new Oracle environment.
Upon updating the variables, the packages expressions update as expected, however, when saving the file to disk, the updated variables aren't saved and the values revert back to the original values.
How are variables updated in .dtsx packages that will allow changes to be saved?
We are using sql server 2005 with java and the last version of driver JDBC, some querys show bad performance when you send by application but if you use sql query analyzer the performance is excellent. We have take a profiler trace and saw that Java call SP_PREPEXEC when it makes a call of preparestatement. We taken the sentence from profiler (with SP_PREPEXEC) and saw the same problem, the query plan is bad, but if we avoid use the prepare statement the query works fine and the performance problem is overcome. Since we have the application with java and use every time the preparedstatement sentence from java, it is very expensive for us , change the code. Do you have any solution for these problem?
I am trying to use the export wizard to export to a MS Access file, using the provide source query option. I get the error below when pasting the query in. The query does run successfully in SSMS, it is a long running query. About 8 minutes to complete.
TITLE: SQL Server Import and Export Wizard ------------------------------ The statement could not be parsed. ------------------------------ ADDITIONAL INFORMATION: Deferred prepare could not be completed. Query timeout expired (Microsoft SQL Native Client)
Hello:I didn't find any documentation that notes save point names are casesensitive, but I guess they are...Stored Proc to reproduce:/* START CODE SNIPPET */If Exists (Select * From sysobjects Where Type = 'P' and Name ='TestSaveTran')Drop Procedure dbo.TestSaveTranGoCreate Procedure dbo.TestSaveTranAsBeginDeclare@tranCount int--Transaction HandlingSelect @tranCount = @@TRANCOUNTIf (@tranCount=0)Begin Tran localtranElseSave Tran localtranBegin Try--Simulate Error While ProcessingRAISERROR('Something bad happened', 16, 1)/*If this proc started transaction then commit it,otherwise return and let caller handle transaction*/IF (@tranCount=0)Commit Tran localtranEnd TryBegin Catch--Rollback to save pointRollback Tran LOCALTRAN --<< NOTE case change--Log Error--Reraise ErrorEnd CatchEndGo--Execute Stored ProcExec dbo.TestSaveTran/*Should receive the following message:Cannot roll back LOCALTRAN. No transaction or savepoint of that namewas found.*//* END CODE SNIPPET */What is really strange, if there is a transaction open, then no erroris thrown. So if you execute as so:/* START CODE SNIPPET */Begin Tran--Execute Stored ProcExec dbo.TestSaveTran/* END CODE SNIPPET */There is no "Cannot roll back LOCALTRAN...." message.Questions:1-)Can someone confirm save point names are case sensitve and this isnot happening because of a server setting?2-)Is this a logic error that I am not seeing in the example codeabove?We have changed our code to store the save point name in a variable,which will hopefully mitigate this "problem".Thx.
Hi,I have a stored procedure that makes an MDX query for me, on SQL 2000, service pack 3 it works fine, but on service pack 4 it stops working with the error:Server: Msg 7399, Level 16, State 1, Line 1OLE DB provider 'MSOLAP.2' reported an error. The provider did not give any information about the error.OLE DB error trace [OLE/DB Provider 'MSOLAP.2' ICommandPrepare::Prepare returned 0x80004005: The provider did not give any information about the error.].and i'f i call @@Error I get the error number 7399.Any ideas as to what might be going on? The stored procedure which worked prior to service pack 4 is as follows:CREATE PROCEDURE MDXTester ( @CustId Varchar(4) ) AS IF NOT EXISTS(SELECT * FROM master..sysservers where srvname = 'CZVCube') BEGIN EXEC sp_addlinkedserver 'CZVCube', '', 'MSOLAP.2', '10.0.41.128', 'CZV' END
DECLARE @OPENQUERY nvarchar(4000), @MDX nvarchar(4000), @LinkedServer nvarchar(4000) SET @LinkedServer = 'CZVCube' SET @OPENQUERY = 'SELECT * FROM OPENQUERY('+ @LinkedServer + ',''' SET @MDX = 'WITH MEMBER [Measures].[YTD NV] AS ''''Sum(YTD(),[Net Value])'''' MEMBER [Measures].[YTD Prev] AS ''''Sum(YTD(),([Measures].[Net value], ParallelPeriod([Fiscal year], 1, [FiscalYear].CurrentMember)))'''' MEMBER [Measures].[YTD Change] AS ''''[Measures].[YTD NV] - [Measures].[YTD Prev]'''', FORMAT_STRING = ''''###,###.00'''' MEMBER [Measures].[YTD Change Perc] AS ''''[Measures].[YTD Change] / [Measures].[YTD Prev]'''', FORMAT_STRING = ''''###,##0.0%'''' MEMBER [Measures].[Monthly Change] AS ''''[Net Value] - ([Net Value],FiscalYear.PrevMember)'''', FORMAT_STRING = ''''###,###.00'''' MEMBER [Measures].[Monthly Change Perc] AS ''''([Monthly Change] / ([Net Value],FiscalYear.PrevMember))'''', FORMAT_STRING = ''''###,##0.0%'''' MEMBER [Measures].[Annual Change] AS ''''[Net Value] - ([Measures].[Net value], ParallelPeriod([Fiscal year], 1, [FiscalYear].CurrentMember))'''', FORMAT_STRING = ''''###,###.00'''' MEMBER [Measures].[Annual Change Perc] AS ''''([Annual Change] / ([Measures].[Net value], ParallelPeriod([Fiscal year], 1, [FiscalYear].CurrentMember)))'''', FORMAT_STRING = ''''###,##0.0%'''' MEMBER [Measures].[12 mth mov av] AS ''''Avg([FiscalYear].CurrentMember.Lag(11):[FiscalYear].CurrentMember, [Measures].[Net Value])'''' SELECT {[Measures].[Net Value] , [Measures].[YTD NV], [Measures].[YTD Prev],[Measures].[Monthly Change], [Measures].[Monthly Change Perc], [Measures].[Annual Change], [Measures].[Annual Change Perc], [Measures].[YTD Change], [Measures].[YTD Change Per c], [Measures].[12 mth mov av]} ON COLUMNS, LastPeriods(12, [FiscalYear].[Apr 08]) ON ROWS FROM CZV where [C_CRMID].[' + @CustId + ']' EXEC(@OPENQUERY + @MDX + ''')')
I have 2 SQL servers. And in the first one I have added the second SQL as a Link Server. When I run an SQL statement on the linked server I get the following message. Server: Msg 7202, Level 11, State 1, Line 1Could not find server 'PROD' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.[OLE/DB provider returned message: Deferred prepare could not be completed.] The SQL statement that I am runnins is Select * from openquery(PROD,'Select * from PROD.GMS.dbo.qryDispCL') But when I run only the SQL statement "Select * from PROD.GMS.dbo.qryDispCL" it works perfect. But I need to have the first statement running. Please help. Your valuable feedback is greatly appriciated.
Hello, I am trying to use the Import export wizard to created a package, using the provide source query option. If i just copy the query from a text file and try to paste , sql only accepts it partially. so i saved it as a sql file and then opened it in the window. However, when i click on 'next' or 'parse' , i get the below error.
TITLE: SQL Server Import and Export Wizard
------------------------------ The statement could not be parsed.
------------------------------ ADDITIONAL INFORMATION: Deferred prepare could not be completed. Query timeout expired (Microsoft SQL Native Client)
The query is pretty big, but it executes successfully in the Management Studion Query Explorer window. I had no problem creating a package using DTS with the same query in Sql 2000. I also tried to migrate the package already existing in Sql 2000, but even though i can migrate it successfully , the package does not execute in Sql 2005. Also i tried other queries which are as big as this one, again the query source window during import/export does not seem to accept large queries??? I depend heavily on large queries for my packages, which i run daily. I have not had any issues with this is sql 2000. Can someone help me with this???
I have been struggling with the below transact sql user defined function. I want to use a transact sql variable in an "in" statement. I don't get any results and I am not sure if I am receiving an error or not.
Code:
DECLARE @myval varchar(50),@username varchar(50) DECLARE @rolelist varchar(2000) SET @rolelist = '' SET @myval = 'user a,user b' select @myval = ''''+ replace(@myval,',',''',''') + '''' print @myval
DECLARE User_Cursor CURSOR FOR select distinct eusername from euser where eusername in (@myval)
OPEN User_Cursor
FETCH NEXT FROM User_Cursor INTO @username
SET @myval = @username SET @rolelist = @username WHILE @@FETCH_STATUS = 0 BEGIN SET @rolelist =+ @rolelist + ',' + @username
FETCH NEXT FROM User_Cursor INTO @username END CLOSE User_Cursor DEALLOCATE User_Cursor print @myval print 'rolelist' + @rolelist GO
I am at a loss any suggestions would be greatly appreciated.
Set @Test='SELECT VIOXX_LastName + '' + VIOXX_FirstName + '' + CONVERT(varchar(50), VIOXX_Number) AS PlaintiffsName, VIOXX_Number FROM tblPlaintiff WHERE VIOXX_Number NOT IN(SELECT VIOXX_Number FROM tblCase_Plaintiff) OR VIOXX_Number IN (SELECT tblCase_Plaintiff.VIOXX_Number FROM tblCase INNER JOIN tblCase_Plaintiff ON tblCase.Case_Number = tblCase_Plaintiff.Case_Number WHERE (tblCase.Status = ''InActive'')) ORDER BY VIOXX_Number, VIOXX_LastName' Select @Test
and get the following result: SELECT VIOXX_LastName + ' + VIOXX_FirstName + ' + CONVERT(varchar(50), VIOXX_Number) AS PlaintiffsName, VIOXX_Number FROM tblPlaintiff WHERE VIOXX_Number NOT IN(SELECT VIOXX_Number FROM tblCase_Plaintiff) OR VIOXX_Number IN (SELECT
the latter part of my original text is not stored in the variable. Is there some limitation on the number of characters for a local variable in transact sql?
I am running the following query trying to return server properties across a linked server. I want to store the results in a table on the server where I an running the query.
DECLARE @BuildClrVersionx nvarchar(128)
SET @BuildClrVersionx =
(SELECT *
FROM OPENQUERY(LKMSSQLXYZ01, 'CONVERT(nvarchar(128),SERVERPROPERTY("BuildClrVersion")'))
I am getting the following errors:
OLE DB provider "SQLNCLI" for linked server "LKMSSQLADM01" returned message "Deferred prepare could not be completed.".
Msg 8180, Level 16, State 1, Line 1
Statement(s) could not be prepared.
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'CONVERT'.
If you have any ideas how I can run this query across a linked server I would appreciate it.
I am using SQL Server Destinations in my data flow tasks. I'm running this package in the server until i encountered this error:
OnError,,,LOAD AND UPDATE Dimension Tables,,,10/24/2007 1:22:23 PM,10/24/2007 1:22:23 PM,-1071636367,0x,Unable to prepare the SSIS bulk insert for data insertion. OnError,,,Load Dimensions,,,10/24/2007 1:22:23 PM,10/24/2007 1:22:23 PM,-1071636367,0x,Unable to prepare the SSIS bulk insert for data insertion. OnError,,,Discount Reason, ISIS Condition, ISIS Defect, ISIS Repair, ISIS Section, ISIS Symptom, Job Status, Parts, Purchase SubOrder Type, Service Contract, Service Reason, Service Type, TechServiceGrp, WarrantyType, Branch, Wastage Reason,,,10/24/2007 1:22:23 PM,10/24/2007 1:22:23 PM,-1073450974,0x,SSIS Error Code DTS_E_PROCESSINPUTFAILED. The ProcessInput method on component "Dim_T_ISISDefect" (56280) failed with error code 0xC0202071. The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running. There may be error messages posted before this with more information about the failure.
What could be the reason for this? I don't usually have an error.
I have 24 tables named tblData1 ... tblData24 and I have a scheduledjob that runs successfully to delete all data older than 31 days.My problem is that I need to keep at least one record in each tablefor the aggregate function max() to work in one of my application'sfunctions, as if there are no records the result is null.Although I have figured out a workaround in the function using max() Iwould like to know how to change my script.Functionally I would like to get the max() value of the ID column(autoincrementing) and then add to the where "And ID <> @maxID".I have tried a few options and come unstuck with scope of variables,and tried to use a temp table to store the max values for the 24tables and got no where. Can anyone help ?Working script without the @maxID bit:-DECLARE @days VARCHAR(12)DECLARE @intData intDECLARE @SQL1 VARCHAR(2000)set @Days = 31set @intData = 1While @intData<=24BeginSET @SQL1 = 'DELETE FROM [DB1_SQL].[dbo].[tblData'+rtrim(CONVERT(char(2), @intData)) + '] Wheredatediff(Day,Datim,getdate())> '+ @daysEXEC(@SQL1)/*print @SQL1*/set @intData= @intData + 1Endgo
CREATE TABLE dbo.MyEmployees ( EmployeeID smallint NOT NULL, FirstName nvarchar(30) NOT NULL, LastName nvarchar(40) NOT NULL, Title nvarchar(50) NOT NULL, DeptID smallint NOT NULL, ManagerID int NULL, CONSTRAINT PK_EmployeeID PRIMARY KEY CLUSTERED (EmployeeID ASC) );
-- Populate the table with values.
INSERT INTO dbo.MyEmployees VALUES (1, N'Ken', N'Sánchez', N'Chief Executive Officer',16,NULL) ,(273, N'Brian', N'Welcker', N'Vice President of Sales',3,1) ,(274, N'Stephen', N'Jiang', N'North American Sales Manager',3,273) ,(275, N'Michael', N'Blythe', N'Sales Representative',3,274)
I'm trying to figure out the best way to write a script to deploy environment variables to different servers. To create the variable I'm currently using catalog. create_environment_variable. I want to wrap that in an if not exist statement.I had thought about just blowing away all the variables and recreating them but I thought that wouldn't go over well in prod. I wasn't sure if by deleting the variable, references to the variable would be lost.
Is there any way to convert a bind variable, which is a list of integer or string values, to nested table in MS SQL Server. I am looking for something like
CAST in Oracle, which converts a varray type column into a nested table. Do we have something like this in SQL Server.
in Oracle:
SELECT CAST(s.addresses AS address_book_t) FROM states s WHERE s.state_id = 111;
I have read about Table valued Parameter, but I am looking for another solution.
I am building as Search page whereby a user passes in a variable and depending on the variable type, different results will come back ...if the search criteria is '123 somewhere' it would be a string and we would search the address field. If the search criteria is '123' i want to search the address field as well as the id field.that being said, in TSQL is there a way to determine if the variable coming in is a string or an int?
Everything about this query works except I'm trying to capture the @companyid (which is a variable) into a column in my table via my select statement.
My error is Invalid column name 'A113', etc. However it is the A113 I'm trying to insert into the first column of the table SAP_GLsummary
-- retrieves a list of gl balances from all companies truncate table sap_glsummary declare @companyID char(6) declare c_company cursor for select INTERID from dbo.GP_Interid open c_company fetch next from c_company into @companyID
I am new to sql sever management studio express, but a long time query analyzer user. This is a very basic question.
I want to change the default directory in sql server management studio express so that when I go to save a query, it is already pointed to the correct one. Where do I change that?
Having searched the forum, this one clearly has form... However beyond assisting those who have fallen at the first hurdle (i.e. forgetting/not knowing that they cannot execute the package remotely to the instance of SQL Server into which they are inserting), the issues raised by others have not been addressed. Thus I am bringing nothing new to the table here - just providing an executive summary of problems which others have run into, written about, but not received answers for.
First the complete error: Description: Unable to prepare the SSIS bulk insert for data insertion. End Error Error: 2008-01-15 04:55:27.58 Code: 0xC004701A Source: <xxx> DTS.Pipeline Description: component "<xxx> failed the pre-execute phase and returned error code 0xC0202071. End Error DTExec: The package execution returned DTSER_FAILURE (1). Started: 4:53:34 AM Finished: 5:00:00 AM Elapsed: 385.384 seconds. The package execution failed. The step failed.
Important points
It mostly works - It produces no error more than 9 times out of 10.
It fails on random dataflows - My package has several dataflows, (mostly) executing concurrently. Where the error occurs it does not do so on the same dataflow each time: on one run it'll fail on dataflow A whilst B,C,D and E succeed, then A-E will all succeed (and continue doing so for the next ten runs thereafter), and then the error recurs for dataflow D, with A,B,C and E all succeeding. Hope someone has something interesting to say,
In a t-sql 2012, I want to declare variables with multiple values and I am having problems since sql server thinks I am working with numbers when I am really working with character and bit values. Here is a copy of the sql that I am trying to use:
DECLARE @Account varchar(100) DECLARE @Processed bit set @Account = '58100,98326,09897' set @Processed ='0,1'
Thus would you show me what I can do so that the sql server knows that I want the values in the set states above to be varchar or character value for @Account and bit value for @Processed?
Trying to create a report... Report should show * documents on hold then depending on the "on-hold type" look in the corresponding table and SELECT a few fields. Here is what I have. Where do I SET the @profile variable to return the profile from my queue table?
DECLARe @profilevarchar(256) SELECT q.[profile],q.on_hold,q.on_hold_message,q.dbc_state FROM QueueASq
So I was looking at the code for the proc created by Ola's script and noticed a number of variable declarations happening early on (like at line 10) but these variable declarations do not have the DECLARE keyword prefacing the variable identifier.
Then, a couple lines lower, a new batch of variables are declared, but this time with the DECLARE keyword. I was under the impression that you always needed the DECLARE. Is it a scope thing? Like related to the fact the first set of variables are before the stored proc's begin statement?
USE [master] GO /****** Object: StoredProcedure [dbo].[DatabaseBackup] Script Date: 7/20/2015 2:23:36 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[DatabaseBackup]
I tend to learn from example and am used to powershell. If for instance in powershell I wanted to get-something and store it in a variable I could, then use it again in the same code. In this example of a table order items where there are order_num, quantity and item_prices how could I declare ordertotal as a variable then instead of repeating it again at "having sum", instead use the variable in its place?
Any example of such a use of a variable that still lets me select the order_num, ordertotal and group them etc? I hope to simply replace in the "having section" the agg function with "ordertotal" which bombs out.
select order_num, sum(quantity*item_price) as ordertotal from orderitems group by order_num having sum(quantity*item_price) >=50 order by ordertotal;
I need to create an output from a T-SQL query that picks a numeric variable and uses the print function to output with leading zeroes if it is less than three characters long when converted to string. For example if the variable is 12 the output should be 012 and if the variable is 3 the output should be 003.
Presently the syntax I am using is PRINT STR(@CLUSTER,3) . But if @CLUSTER which is numeric is less than three characters I get spaces in front.