Search Results

Search found 1208 results on 49 pages for 'tsql'.

Page 19/49 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • Data tweaking code runs fine when executed directly - but never stops when used in trigger

    - by MBaas
    I have written some code to ensure that items on an order are all numbered (the "position number" or "item number" has been introduced only recently and we did not want to go and change all related code - as it is "asthetics only" and has no functional impact.) So, the idea is to go and check for an records that jave an itemno of NULL or 0 - and then compute one and assign it. When executing this code in a query window, it works fine. When putting it into an AFTER INSERT-trigger, it loops forever. So what is wrong here? /****** Objekt: Trigger [SetzePosNr] Skriptdatum: 02/28/2010 20:06:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TRIGGER [SetzePosNr] ON [dbo].[bestellpos] AFTER INSERT AS BEGIN DECLARE @idb int DECLARE @idp int DECLARE @pnr int SELECT @idp=id,@idb=id_bestellungen FROM bestellpos WHERE posnr IS NULL OR posnr=0 WHILE @idp IS NOT NULL BEGIN SELECT @pnr = 1+max(posnr) FROM bestellpos WHERE id_bestellungen = @idb print( 'idp=' + str(@idp) + ', idb=' + str(@idb) + ', posnr=' + str(@pnr)) UPDATE bestellpos SET posnr=@pnr WHERE id=@idp SELECT @idp=id,@idb=id_bestellungen FROM bestellpos WHERE posnr IS NULL OR posnr=0 END END

    Read the article

  • Counting consecutive items within MS SQL

    - by Greg
    Got a problem with a query I'm trying to write. I have a table that lists people that have been sent an email. There is a bit column named Active which is set to true if they have responded. But I need to count the number of consecutive emails the person has been inactive since either their first email or last active email. For example, this basic table shows one person has been sent 9 emails. They have been active within two of the emails (3 & 5). So their inactive count would be 4 as we are counting from email number 6 onwards. PersonID(int) EmailID(int) Active(bit) 1 1 0 1 2 0 1 3 1 1 4 0 1 5 1 1 6 0 1 7 0 1 8 0 1 9 0 Any pointers or help would be great. Regards Greg

    Read the article

  • Get percentiles of data-set with group by month

    - by Cylindric
    Hello, I have a SQL table with a whole load of records that look like this: | Date | Score | + -----------+-------+ | 01/01/2010 | 4 | | 02/01/2010 | 6 | | 03/01/2010 | 10 | ... | 16/03/2010 | 2 | I'm plotting this on a chart, so I get a nice line across the graph indicating score-over-time. Lovely. Now, what I need to do is include the average score on the chart, so we can see how that changes over time, so I can simply add this to the mix: SELECT YEAR(SCOREDATE) 'Year', MONTH(SCOREDATE) 'Month', MIN(SCORE) MinScore, AVG(SCORE) AverageScore, MAX(SCORE) MaxScore FROM SCORES GROUP BY YEAR(SCOREDATE), MONTH(SCOREDATE) ORDER BY YEAR(SCOREDATE), MONTH(SCOREDATE) That's no problem so far. The problem is, how can I easily calculate the percentiles at each time-period? I'm not sure that's the correct phrase. What I need in total is: A line on the chart for the score (easy) A line on the chart for the average (easy) A line on the chart showing the band that 95% of the scores occupy (stumped) It's the third one that I don't get. I need to calculate the 5% percentile figures, which I can do singly: SELECT MAX(SubQ.SCORE) FROM (SELECT TOP 45 PERCENT SCORE FROM SCORES WHERE YEAR(SCOREDATE) = 2010 AND MONTH(SCOREDATE) = 1 ORDER BY SCORE ASC) AS SubQ SELECT MIN(SubQ.SCORE) FROM (SELECT TOP 45 PERCENT SCORE FROM SCORES WHERE YEAR(SCOREDATE) = 2010 AND MONTH(SCOREDATE) = 1 ORDER BY SCORE DESC) AS SubQ But I can't work out how to get a table of all the months. | Date | Average | 45% | 55% | + -----------+---------+-----+-----+ | 01/01/2010 | 13 | 11 | 15 | | 02/01/2010 | 10 | 8 | 12 | | 03/01/2010 | 5 | 4 | 10 | ... | 16/03/2010 | 7 | 7 | 9 | At the moment I'm going to have to load this lot up into my app, and calculate the figures myself. Or run a larger number of individual queries and collate the results.

    Read the article

  • Check if I can execute some sql-command

    - by Alexander Stalt
    I'm using ADO .NET and MS SQL Server 2008. I have a connection object to a server and a command: SqlConnection conn = /* my connection*/; string cmd = "some_sql_command"; I want to check if SQL Server can execute cmd. I don't want to execute cmd, but I want to know If SQL Server can execute it. cmd can be any single SQL statement, it's not a procedure, transaction or multiple commands etc..

    Read the article

  • T-SQL out of order insert

    - by tearman
    Basically I have a User-Defined Table Type (for use as a table-valued variable) which I'm referencing in a stored procedure that effectively just calls two other stored procedures, then inserts those values into the table type. Id est INSERT INTO @tableValuedVariable (var1, var2, var3, var4, var5) EXEC [dbo].StoredProcedure1; INSERT INTO @tableValuedVariable (var1, var2, var5) EXEC [dbo].StoredProcedure2; You can probably already tell what I'm going to ask. Basically StoredProcedure2 only returns a few of the values the table is set to hold, and I'd like those other variables to just be null (as defined as default). Only SQL is complaining that I'm not specifying all the variables available to that table. The return datasets can be quite sizable so I'd like to avoid loops and such for obvious reasons. Thanks for any help.

    Read the article

  • How to Retrieve Dynamic Columns?

    - by user2514925
    I have a table: EmpId FirstName LastName Domain Vertical Account City 345 Priya Palanisamy DotNet LS Abbott Chennai 346 Kavitha Amirtharaj DotNet CG Diageo Chennai 647 Kala Haribabu DotNet IME IMS Chennai I want to take the particular columns dynamically. I am using the following procedure but I can take only one column at a time: create PROC columnlist ( @COLUMNS VARCHAR(1000) ) AS BEGIN DECLARE @sql nvarchar(max) = 'SELECT '+ @COLUMNS + ' FROM Table'; exec sp_executesql @sql,N'' END

    Read the article

  • Insert rownumber repeatedly in records in t-sql.

    - by jeff
    Hi, I want to insert a row number in a records like counting rows in a specific number of range. example output: RowNumber ID Name 1 20 a 2 21 b 3 22 c 1 23 d 2 24 e 3 25 f 1 26 g 2 27 h 3 28 i 1 29 j 2 30 k I rather to try using the rownumber() over (partition by order by column name) but my real records are not containing columns that will count into 1-3 rownumber. I already try to loop each of record to insert a row count 1-3 but this loop affects the performance of the query. The query will use for the RDL report, that is why as much as possible the performance of the query must be good. any suggestions are welcome. Thanks

    Read the article

  • T-SQL Table Variable Creating PHYSICAL Table!

    - by Mike
    OMG! What am I doing wrong? declare @WTF TABLE ( OrderItemId int ) SELECT TOP 20 OrderItemId as OrderItemId INTO [@WTF] FROM ac_OrderItems SELECT * FROM [@WTF] Problem A: This creates a PHYSICAL table called @WTF. WHY?? I thought this was in memory only?! Problem B: The last line of code, if I do select * from @WTF... WITHOUT the [ ], it returns NOTHING. What is the significance of the [ ]? I need serious help. I'm losing my MIND! Thanks in advance.

    Read the article

  • SQL Server 2005 - query with case statement

    - by user329266
    Trying to put a single query together to be used eventually in a SQL Server 2005 report. I need to: Pull in all distinct records for values in the "eventid" column for a time frame - this seems to work. For each eventid referenced above, I need to search for all instances of the same eventid to see if there is another record with TaskName like 'review1%'. Again, this seems to work. This is where things get complicated: For each record where TaskName is like review1, I need to see if another record exists with the same eventid and where TaskName='End'. Utimately, I need a count of how many records have TaskName like 'review1%', and then how many have TaskName like 'review1%' AND TaskName='End'. I would think this could be accomplished by setting a new value for each record, and for the eventid, if a record exists with TaskName='End', set to 1, and if not, set to 0. The query below seems to accomplish item #1 above: SELECT eventid, TimeStamp, TaskName, filepath FROM (SELECT eventid, TimeStamp, filepath, TaskName, ROW_NUMBER() OVER(PARTITION BY eventid ORDER BY TimeStamp DESC) AS seq FROM eventrecords where ((TimeStamp >= '2010-4-1 00:00:00.000') and (TimeStamp <= '2010-4-21 00:00:00.000'))) AS T WHERE seq = 1 order by eventid And the query below seems to accomplish #2: SELECT eventid, TimeStamp, TaskName, filepath FROM (SELECT eventid, TimeStamp, filepath, TaskName, ROW_NUMBER() OVER(PARTITION BY eventid ORDER BY TimeStamp DESC) AS seq FROM eventrecords where ((TimeStamp >= '2010-4-1 00:00:00.000') and (TimeStamp <= '2010-4-21 00:00:00.000')) and TaskName like 'Review1%') AS T WHERE seq = 1 order by eventid This will bring back the eventid's that also have a TaskName='End': SELECT eventid, TimeStamp, TaskName, filepath FROM (SELECT eventid, TimeStamp, filepath, TaskName, ROW_NUMBER() OVER(PARTITION BY eventid ORDER BY TimeStamp DESC) AS seq FROM eventrecords where ((TimeStamp >= '2010-4-1 00:00:00.000') and (TimeStamp <= '2010-4-21 00:00:00.000')) and TaskName like 'Review1%') AS T WHERE seq = 1 and eventid in (Select eventid from eventrecords where TaskName = 'End') order by eventid So I've tried the following to TRY to accomplish #3: SELECT eventid, TimeStamp, TaskName, filepath FROM (SELECT eventid, TimeStamp, filepath, TaskName, ROW_NUMBER() OVER(PARTITION BY eventid ORDER BY TimeStamp DESC) AS seq FROM eventrecords where ((TimeStamp >= '2010-4-1 00:00:00.000') and (TimeStamp <= '2010-4-21 00:00:00.000')) and TaskName like 'Review1%') AS T WHERE seq = 1 and case when (eventid in (Select eventid from eventrecords where TaskName = 'End') then 1 else 0) as bit end order by eventid When I try to run this, I get: "Incorrect syntax near the keyword 'then'." Not sure what I'm doing wrong. Haven't seen any examples anywhere quite like this. I should mention that eventrecords has a primary key, but it doesn't seem to help anything when I include it, and I am not permitted to change the table. (ugh) I've received one suggestion to use a cursor and temporary table, but am not sure how badley that would bog down performance when the report is running. Thanks in advance.

    Read the article

  • Protocol error in TDS stream

    - by jasonline
    What are the possible causes of this type of error - "[Microsoft][ODBC SQL Server Driver]Protocol error in TDS stream"? And how can this be fixed? My application runs in C++ calling stored procedures implemented in SQL Server. There's this one SP (containing select and update statements) that causes this problem, after which all succeeding queries will return that the cursor is in an invalid state. I've checked the SP but I don't see any possible problem.

    Read the article

  • Variable as numeric sent to stored procedure (SQL Server 2005)

    - by TimCarrett
    I see that with SQL Server 2005 you can pass a parameter as numeric e.g. create procedure dbo.TestSP @Param1 numeric as But what does this equate to? E.g. Numeric(10,0), Numeric(9,2), etc? We have some Developers here who are using this instead of the correct definition for the field that this parameter is going to be used against e.g. instead of using Numeric(10, 0) for the parameter @Param1. Also are there any underlying performance issues with using Numeric instead of the data type defined against the field in the table? Many thanks.

    Read the article

  • 3 tier application pattern suggestion

    - by Maxim Gershkovich
    I have attempted to make my first 3 tier application. In the process I have run into one problem I am yet to find an optimal solution for. Basically all my objects use an IFillable interface which forces the implementation of a sub as follows Public Sub Fill(ByVal Datareader As Data.IDataReader) Implements IFillable.Fill This sub then expects the Ids from the datareader will be identical to the properties of the object as such. Me.m_StockID = Datareader.GetGuid(Datareader.GetOrdinal("StockID")) In the end I end up with a datalayer that looks something like this. Public Shared Function GetStockByID(ByVal ConnectionString As String, ByVal StockID As Guid) As Stock Dim res As New Stock Using sqlConn As New SqlConnection(ConnectionString) sqlConn.Open() res.Fill(StockDataLayer.GetStockByIDQuery(sqlConn, StockID)) End Using Return res End Function Mostly this pattern seems to make sense. However my problem is, lets say I want to implement a property for Stock called StockBarcodeList. Under the above mentioned pattern any way I implement this property I will need to pass a connectionstring to it which obviously breaks my attempt at layer separation. Does anyone have any suggestions on how I might be able to solve this problem or am I going about this the completely wrong way? Does anyone have any suggestions on how I might improve my implementation? Please note however I am deliberately trying to avoid using the dataset in any form.

    Read the article

  • How to make awkward pivot of sql table in MS SQL Server 2005?

    - by Oliver
    I have to rotate a given table from an sql server but a normal pivot just doesn't work (as far as i tried). So has anybody an idea how to rotate the table into the desired format? Just to make the problem more complicated, the list of given labels can vary and it is possible that a new label name can come into at any given time. Given Data ID | Label | Numerator | Denominator | Ratio ---+-----------------+-------------+---------------+-------- 1 | LabelNameOne | 41 | 10 | 4,1 1 | LabelNameTwo | 0 | 0 | 0 1 | LabelNameThree | 21 | 10 | 2,1 1 | LabelNameFour | 15 | 10 | 1,5 2 | LabelNameOne | 19 | 19 | 1 2 | LabelNameTwo | 0 | 0 | 0 2 | LabelNameThree | 15 | 16 | 0,9375 2 | LabelNameFive | 19 | 19 | 1 2 | LabelNameSix | 17 | 17 | 1 3 | LabelNameOne | 12 | 12 | 1 3 | LabelNameTwo | 0 | 0 | 0 3 | LabelNameThree | 11 | 12 | 0,9167 3 | LabelNameFour | 12 | 12 | 1 3 | LabelNameSix | 0 | 1 | 0 Wanted result ID | ValueType | LabelNameOne | LabelNameTwo | LabelNameThree | LabelNameFour | LabelNameFive | LabelNameSix ---+-------------+--------------+--------------+----------------+---------------+---------------+-------------- 1 | Numerator | 41 | 0 | 21 | 15 | | 1 | Denominator | 10 | 0 | 10 | 10 | | 1 | Ratio | 4,1 | 0 | 2,1 | 1,5 | | 2 | Numerator | 19 | 0 | 15 | | 19 | 17 2 | Denominator | 19 | 0 | 16 | | 19 | 17 2 | Ratio | 1 | 0 | 0,9375 | | 1 | 1 3 | Numerator | 12 | 0 | 11 | 12 | | 0 3 | Denominator | 12 | 0 | 12 | 12 | | 1 3 | Ratio | 1 | 0 | 0,9167 | 1 | | 0

    Read the article

  • Why might SQL execute more quickly on SQL Server 2000 when NOT using a stored procedure?

    - by Kofi Sarfo
    I could see nothing wrong with the execution plan. Besides, as I understand it, SQL Server 2000 extended many of the performance benefits of stored procedures to all SQL statements by recognising new T-SQL statements against T-SQL statements of existing execution plans (by retaining execution plans for all SQL statements in the procedure cache, not just stored procedure execution plans) It's a fairly straight forward SELECT statement with sensible table joins, no transactions included or linked servers being referenced within the query and WITH (NOLOCK) table hints applied. The stored procedure was created by dbo and the user has all the necessary permissions. So my question is this: What are the likely reasons for a query to take only a few seconds to run but then take several minutes when identical T-SQL is run via a stored procedure?

    Read the article

  • Help with query

    - by hdoe123
    Hi, I'm trying make a query that looks at a single table and looks to see if a student is a team called CMHT and in a medic team - if they are I don't want to see the result. I only want see if there only in CMHT or medic not both. Would the right direction be using sub query to filer it out? I've done a search on NOT IN but how could you get to see check if its in more then 2 teams are not? Student Team ref 1 CMHT 1 1 Medic 2 2 Medic 3 this would be in the result 3 CMHT 5 this would be in the result So far I've done the following code would I need use a sub query or do a self join and filter it that way? SELECT Table1.Student, Table1.Team, Table1.refnumber FROM Table1 WHERE (((Table1.Team) In ('Medics','CMHT'))

    Read the article

  • How to call an extended procedure from a function

    - by Alan Featherston Lago
    hi im having trouble trying to get the following function to work. CREATE FUNCTION test ( @nt_group VARCHAR(128) ) RETURNS @nt_usr TABLE ( [name] [nchar](128) NULL , [type] [char](8) NULL , [privilege] [char](9) NULL , [mapped login name] [nchar](128) NULL , [permission path] [nchar](128) NULL ) AS BEGIN INSERT INTO @nt_usr EXEC master.dbo.xp_logininfo 'DOMAIN\USER', @nt_group RETURN END As far as i know i should be allowed to call an extended stored procedure, im getting the following error Mes 443, Level 16, State 14 Could it be that xp_logininfo might return different result sets depending on the parameters? When i use openquery i can overcome this by setting this: SET FMTONLY OFF. Does anyone know if there's a similar workaround for my problem?

    Read the article

  • SQL Server 2005, wide indexes, computed columns, and sargable queries

    - by luksan
    In my database, assume we have a table defined as follows: CREATE TABLE [Chemical]( [ChemicalId] int NOT NULL IDENTITY(1,1) PRIMARY KEY, [Name] nvarchar(max) NOT NULL, [Description] nvarchar(max) NULL ) The value for Name can be very large, so we must use nvarchar(max). Unfortunately, we want to create an index on this column, but nvarchar(max) is not supported inside an index. So we create the following computed column and associated index based upon it: ALTER TABLE [Chemical] ADD [Name_Indexable] AS LEFT([Name], 20) CREATE INDEX [IX_Name] ON [Chemical]([Name_Indexable]) INCLUDE([Name]) The index will not be unique but we can enforce uniqueness via a trigger. If we perform the following query, the execution plan results in a index scan, which is not what we want: SELECT [ChemicalId], [Name], [Description] FROM [Chemical] WHERE [Name]='[1,1''-Bicyclohexyl]-2-carboxylic acid, 4'',5-dihydroxy-2'',3-dimethyl-5'',6-bis[(1-oxo-2-propen-1-yl)oxy]-, methyl ester' However, if we modify the query to make it "sargable," then the execution plan results in an index seek, which is what we want: SELECT [ChemicalId], [Name], [Description] FROM [Chemical] WHERE [Indexable_Name]='[1,1''-Bicyclohexyl]-' AND [Name]='[1,1''-Bicyclohexyl]-2-carboxylic acid, 4'',5-dihydroxy-2'',3-dimethyl-5'',6-bis[(1-oxo-2-propen-1-yl)oxy]-, methyl ester' Is this a good solution if we control the format of all queries executed against the database via our middle tier? Is there a better way? Is this a major kludge? Should we be using full-text indexing?

    Read the article

  • Sql Server copying table information between databases

    - by Andrew
    Hi, I have a script that I am using to copy data from a table in one database to a table in another database on the same Sql Server instance. The script works great when I am connected to the Sql Server instance as myself as I have dbo access to both databases. The problem is that this won't be the case on the client's Sql Server. They have seperate logins for each database (Sql Authentication Logins). Does anyone know if there is a way to run a script under these circumstances. The script would be doing something like. use sourceDB Insert targetDB.dbo.tblTest (id, test_name) Select id, test_name from dbo.tblTest Thanks

    Read the article

  • How to reference a sql server with a slash (\) in its name?

    - by Bill Paetzke
    Givens: One SQL Server is named: DevServerA Another is named: DevServerB\2K5 Problem: From DevServerA, how can I write a query that references DevServerB\2K5? I tried a sample, dummy query (running it from DevServerA): SELECT TOP 1 * FROM DevServerB\2K5.master.sys.tables And I get the error: Msg 102, Level 15, State 1, Line 2 Incorrect syntax near '\.'. However, I know my syntax is almost correct, since the other way around works (running this query from DevServerB\2K5): SELECT TOP 1 * FROM DevServerA.master.sys.tables Please help me figure out how to reference DevServerB\2K5 from DevServerA. Thanks.

    Read the article

  • set difference in SQL query

    - by TheObserver
    I'm trying to select records with a statement SELECT * FROM A WHERE LEFT(B, 5) IN (SELECT * FROM (SELECT LEFT(A.B,5), COUNT(DISTINCT A.C) c_count FROM A GROUP BY LEFT(B,5) ) p1 WHERE p1.c_count = 1 ) AND C IN (SELECT * FROM (SELECT A.C , COUNT(DISTINCT LEFT(A.B,5)) b_count FROM A GROUP BY C ) p2 WHERE p2.b_count = 1) which takes a long time to run ~15 sec. Is there a better way of writing this SQL?

    Read the article

  • query to get part of a string

    - by tri
    column1 \\abc\tri\eds\rf1\edr\4ed \\f.d\tri\ef\poe \\ghi0j\tri\gf\rf\k\hg\ose ' ' ' i got some rows like that in a column now i want to get the result set like \\abc\tri\eds \\f.d\tri\ef\ \\ghij\tri\gf simply from first '\' to end of 4th '\'

    Read the article

  • SQL: script to create country, state tables

    - by pcampbell
    Consider writing an application that requires registration for an entity, and the schema has been defined to require the country, state/prov/county data to be normalized. This is fairly typical stuff here. Naming also is important to reflect. Each country has a different name for this entity: USA = states Australia = states + territories Canada = provinces + territories Mexico = states Brazil = states Sweden = provinces UK = counties, principalities, and perhaps more! Most times when approaching this problem, I have to scratch together a list of good countries, and the states/prov/counties of each. The app may be concerned with a few countries and not others. The process is full of pain. It typically involves one of two approaches: opening up some previous DB and creating a CREATE script based on those tables. Run that script in the context of the new system. creating a DTS package from database1 to database2, with all the DDL and data included in the transfer. My goal now is to script the creation and insert of the countries that I'd be concerned with in the app of the day. When I want to roll out Countries X/Y/Z, I'll open CountryX.sql, and load its states into the ProvState table. Question: do you have a set of scripts in your toolset to create schema and data for countries and state/province/county? If so, would you share your scripts here? (U.K. citizens, please feel free to correct me by way of a comment in the use of counties.)

    Read the article

  • Optimizing ROW_NUMBER() in SQL Server

    - by BlueRaja
    We have a number of machines which record data into a database at sporadic intervals. For each record, I'd like to obtain the time period between this recording and the previous recording. I can do this using ROW_NUMBER as follows: WITH TempTable AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Machine_ID ORDER BY Date_Time) AS Ordering FROM dbo.DataTable ) SELECT [Current].*, Previous.Date_Time AS PreviousDateTime FROM TempTable AS [Current] INNER JOIN TempTable AS Previous ON [Current].Machine_ID = Previous.Machine_ID AND Previous.Ordering = [Current].Ordering + 1 The problem is, it goes really slow (several minutes on a table with about 10k entries) - I tried creating separate indicies on Machine_ID and Date_Time, and a single joined-index, but nothing helps. Is there anyway to rewrite this query to go faster?

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >