Quantcast
Channel: SQLServerCentral » SQL Server 2012 » SQL Server 2012 - T-SQL » Latest topics
Viewing all 4901 articles
Browse latest View live

Suggest Datatype

$
0
0
Worked on a new clients data today and saw the columns were all varchar(255) for all the tables.Quickly scanning thru some of the columns I can clearly see this is incorrect.Probably imported from text with no data structure.Does anyone have code that would go thru columns and the data and suggest a datatypeThought this will be an interesting one to do :-)

E-Mail Triggers

$
0
0
My first post here, and a newbie in SQLI have written a few triggers before, This one does not seems to work. Is it my nested select? I'm not getting any errors. Just nothing is e-mailed.[code="sql"]Use ABCTRAININGSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOalter TRIGGER TAXPERCENT ON [dbo].[AP101_VOUCHER_DISTR] AFTER update AS declare @VAT numeric(15,2),@Total numeric(15,2),@VATPERCENT numeric(15,2),@Voucher nvarchar(max),@AMT numeric(15,2),@GL numeric(15,2)Select @Voucher = i.ap101_voucher,@AMT = i.ap101_amt,@GL = i.AP101_GL_ACCT,@VAT = (select sum(iif(@GL = '70102501110' or @GL = '70102501120',@AMT,0))),@Total = (select sum(@AMT)),@VATPERCENT = @VAT/(@Total-@VAT)from inserted iif @VATPERCENT <> 0.140BEGINDECLARE @msg nvarchar(MAX)Declare @Subj varchar(MAX)Declare @EM nvarchar(MAX)SET @msg = 'The VAT on this Voucher ' + @Voucher + ' ' + 'does not equal 14% ' + ' ' + @VATPERCENTSET @Subj = 'Voucher Error'set @EM = 'xxxxxx@company.co.za'EXEC msdb.dbo.sp_send_dbmail @importance ='High',@recipients=@EM,@body= @msg,@subject = @Subj,@body_format = 'HTML', @profile_name = 'ABC Profile'END[/code]Any help will be appreciatedThanks

Cursors / without Cursors / SSIS

$
0
0
I have a table with 10 columns(col1 varchar,col2 int,….name varchar(max),…col10)I have to print out text extracts of all rows for each distinct name value in the table.The text extracts should be named this way name_datestamp.txt (yyyymmdd)for value of name and the text extracts should be in tab delimited format.If name is sun and there are 10 rows with sun as value under name column then text extract must be sun_datestamp.txt(yyyymmdd) with 10 rows in it.If name is moon then text extract must be moon_datestamp.txt(yyyymmdd)I need to run this every month?How do I achieve this ->using Cursors without cursors or using SSIS.

Dazed and Confused

$
0
0
Hello,I have an SQL query that is not returning any data for one of the columns. The data for this column is coming from a table and there is no other data coming from this table, just this one column. I am left joining to this table.The join looks like LEFT JOIN DataStore.dbo.t_YearData YD ON ( YD.Year = Z.ExpYear AND YD.Framework = 'Year End' AND YD.[Level] = 'All' AND YD.[Type] = 'T' )Z is the alias for the main table I am joining to.If I change the join to LEFT JOIN DataStore.dbo.t_YearData YD ON ( YD.Year = Z.ExpYear AND YD.Framework LIKE 'Y%' AND YD.[Level] LIKE 'A%' AND YD.[Type] = 'T' )I have data returned to the column. What I don't understand is if I doSELECT * FROM DataStore.dbo.t_YearData YDWHERE YD.Year = '2013'AND YD.Framework = 'Year End'AND YD.[Level] = 'All'AND YD.[Type] = 'T'The data is returned no problems.I don't understand why my original join doesn't work but does as a where clause on a direct select. I am substituting the text 2013 for Z.ExpYear but this value does defiantly exist in my table along with the data I am trying to retrieve.ThanksEliza

SQL Server Users with default Schemas and dbo as owner issue

$
0
0
Using SQL Server 2012, I am trying to create a user with a default schema which is the same as the username but with dbo as the owner of the schema. I am getting the following error when trying to create a table as the log in user:"Msg 2760, Level 16, State 1, Line 2The specified schema name "TestUser1" either does not exist or you do not have permission to use it."Here is my attempt to set up a user schema (the user's default schema) with dbo as owner. I would like for the user to be able to create objects within his\her schema which is owned by dbo. I hope I am not making this more difficult than it should be.--NOTE: In Step 4, I had to change the schema owner to dbo in order to assign permissions. With TestUser1 as the schema owner, it returns the following error: "Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema, sys, or yourself."--1. Create Login.USE [master]GOCREATE LOGIN TestLogin1 WITH PASSWORD='?????????', DEFAULT_DATABASE=ST_Demo;GO--2. Create a database user, map it to a login and add a default schema. This step does not create a schema. --NOTE: At this point, the user is linked to his/her schema but the schema does not exists.USE ST_Demo;GOCREATE USER TestUser1 FOR LOGIN TestLogin1 WITH DEFAULT_SCHEMA=TestUser1;--3. Create a Schema.--The AUTHORIZATION section on the syntax identifies the owner.--This section is optional, and if you do not include it, the owner--will be the dbo user.USE ST_Demo;GOCREATE SCHEMA TestUser1 AUTHORIZATION TestUser1; GO--4. Apply Permissions on Schemas.--NOTE: Had to changed the schema owner to dbo in order to assign permissions.--With TestUser1 as the schema owner, it returns the following error:--Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema, sys, or yourself.USE ST_Demo;GOALTER AUTHORIZATION ON SCHEMA::[TestUser1] TO [dbo] GOGRANT ALTER ON SCHEMA::[TestUser1] TO [TestUser1]GOGRANT CONTROL ON SCHEMA::[TestUser1] TO [TestUser1]GOGRANT SELECT ON SCHEMA::[TestUser1] TO [TestUser1]GOGRANT DELETE ON SCHEMA::[TestUser1] TO [TestUser1]GOGRANT INSERT ON SCHEMA::[TestUser1] TO [TestUser1]GOGRANT UPDATE ON SCHEMA::[TestUser1] TO [TestUser1]GOGRANT CREATE TABLE TO TestUser1;GO5. Test TestLogin1. Log in as TestLogin1 and execute the Create Table Statement.--Create Table.USE ST_Demo;GOCREATE TABLE Customer( CustomerID int NOT NULL IDENTITY(1,1), CustomerName varchar(25) NOT NULL, StateCode char(2) NOT NULL, CreditLimit money NULL ); GOThis is the error it returns with 'dbo' as the owner of the schema.--Msg 2760, Level 16, State 1, Line 2--The specified schema name "TestUser1" either does not exist or you do not have permission to use it.--The above Create Table Statement works, if I set "TestUser1" as the owner of the schema instead of 'dbo':USE ST_Demo;GOALTER AUTHORIZATION ON SCHEMA::[TestUser1] TO [TestUser1] GOI have been told that when I created the users, I gave them a default schema with the same name as the user name and this caused the error. Is this true? I still thought if I created a schema (no matter the name whether it is username or HumanResources or Development) that this would work but evidently not. I guess schemas should not be created with user names even though SQL Server allows it. Schemas should be created by department or function. When you create the users, give them a default schema, not one that has the same name as the users.Separation of users and schemas is the best practice, right? So, I guess when I create a user I would like to eliminate users from owning objects, including schemas. I should create a user, create a schema with 'dbo' as the owner, assigned the schema as the default schema for the user. When the user creates an object, the object should be created in the user's default schema. However, 'dbo' should still be the owner of the schema which is what I am trying to accomplish.From my reading and understanding:•Database schema names are distinct from user names.•Multiple users may share a schema, which means it can hold objects owned by multiple users.•Permissions to act inside the schema may be granted to individual users.•Database users can be dropped without changing objects in schemas, which is a big difference between Oracle and SQL Server.Considering the first bullet above (•Database schema names are distinct from user names), I wonder why SQL Server allows you to still create a schema that has the same name as a database user?When I get to work on Monday, I will try the following and I guess it should work because I have a schema name that is separate from the user name.Create TestLogin1 and TestLogin2.Create User TestUser1 for Login TestLogin1 with Default_Schema as Development.Create User TestUser2 for Login TestLogin2 with Default_Schema as Development.Create Development Schema (this schema could be called HumanResources or Development). Since I can not call the schema the same name as the User or it would cause problems.Make the Development Schema the default schema for the TestUser1 and TestUser2.When the users TestUser1 and TestUser2 create objects, the objects would be created in their default schema (Development Schema).Just wonderiing if I am headed in the right direction and should the goal be to have 'dbo' own the schemas but allow database users to create objects within the schemas. Thanks, Kevin

Time Range

$
0
0
Hello Everyone,I am having difficulties to display data between 22:00 and 05:59.So the following query is generally working except for the above time range :[code="sql"]select TOP(1) CONVERT(DECIMAL(18,2),REPLACE(CONVERT(VARCHAR(5),CONVERT(DATETIME,EndTime),108),':','.'))-CONVERT(DECIMAL(18,2),REPLACE(CONVERT(VARCHAR(5),CONVERT(DATETIME,@DAte),108),':','.')) FROM ProductionShift WHERE CAST(@date AS time(5)) BETWEEN CAST(replace(convert(varchar,@date,110),'/','-')+' '+[b]StartTime[/b]+':00.000' AS time(5)) AND CAST(replace(convert(varchar,@date,110),'/','-')+' '+[b]EndTime[/b]+':00.000' AS time(5))[/code]The columns StartTime and EndTime are varchars(ie 06:00, 13:59)!They can't be changed. My thought was to short of 'construct' the date so can check the range properly. Like I mentioned, it works for all the shifts EXCEPT the night one!!Any help, would be really appreciated.Thanks,V

How to collect data from a remote server using @@VERSION and/or SERVERPROPERTY('ProductVersion') etc

$
0
0
Hi,How can I query a remote server using server functions and save that data to a local table?I have a simple proc that collects server information from a linkedserver.EXEC usp_MyProc 'Param' gives the desired results.INSERT <Tbl> EXEC usp_MyProc 'Param' gives an error. See below in the code.[code="sql"]IF OBJECT_ID('TempDB..#TmpDBs') IS NULLBEGIN CREATE TABLE #TmpDBs ( SvrName Varchar(128) NOT NULL, DBNAme Varchar(128) NOT NULL, ComPatLvl TinyInt NOT NULL )ENDGOCREATE PROC usp_TmpDBs (@Svr Varchar(128))ASBEGIN-- Testing parameter--DECLARE @Svr Varchar(128)--SELECT @Svr = 'Svr002'-- VariablesDECLARE @SQL Varchar(MAX), @SQLSP Varchar(MAX)--BEGIN TRAN DELETE #TmpDBs WHERE SvrName = @Svr --Code 1: SET @SQL = ' SELECT @@SERVERNAME SvrName, D.Name, D.[Compatibility_Level] FROM ['+@Svr+'].[master].sys.Databases D' -- Both of these SET lines return the same error. See below for the error. SET @SQLSP = 'EXEC ('''+@SQL+''') AT '+@Svr --SET @SQLSP = 'EXEC ['+@Svr+'].[master].[dbo].[sp_ExecuteSQL] @Statement = N'''+@SQL + '''' EXEC (@SQLSP)-- Code 2:/* This code works fine but cannot use functions such as @@VERSION or SERVERPROPERTY('ProductVersion') etc.. SET @SQL = 'INSERT #TmpDBs SELECT '''+@Svr+''' SvrName, D.Name, D.[Compatibility_Level] FROM ['+@Svr+'].[master].sys.Databases D' EXEC (@SQL)*/ --COMMIT TRANENDEXEC usp_TmpDBs @Svr = 'Svr002' -- Returns the desired results, when not using BEGIN / COMMIT TRANINSERT #TmpDBs EXEC usp_TmpDBs @Svr = 'Svr002' -- gives error :/*OLE DB provider "SQLNCLI11" for linked server "Svr002" returned message "The partner transaction manager has disabled its support for remote/network transactions.".Msg 7391, Level 16, State 2, Line 1The operation could not be performed because OLE DB provider "SQLNCLI11" for linked server "Svr002" was unable to begin a distributed transaction.*//* After turning on DTC on Svr002. OLE DB provider "SQLNCLI" for linked server "Svr002" returned message "No transaction is active.".Msg 7391, Level 16, State 2, Line 1The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "Svr002" was unable to begin a distributed transaction.*/[/code]I have tried the following links to no avail.[url=http://social.msdn.microsoft.com/Forums/en-US/7172223f-acbe-4472-8cdf-feec80fd2e64/the-partner-transaction-manager-has-disabled-its-support-for-remotenetwork-transactions]the-partner-transaction-manager-has-disabled-its-support-for-remotenetwork-transactions[/url][url=http://itknowledgeexchange.techtarget.com/sql-server/how-to-configure-dtc-on-windows-2008/]how-to-configure-dtc-on-windows-2008[/url][url=http://itknowledgeexchange.techtarget.com/sql-server/how-to-configure-dtc-on-windows-2003/]how-to-configure-dtc-on-windows-2003[/url]Local machines:Windows 7 SQL + 2012 Express Windows 2003 Enterprise + SQL 2005 EnterpriseRemote machine Windows 2008 R2 Enterprise + SQL 2008 R2 Enterprise

Index cannot be created on view because the underlying object has a different owner

$
0
0
Hello Guys,We are getting the below error while creating the clustered index on the index view:"Index cannot be created on view because the underlying object has a different owner"The schemas of the "base table" referred in the view and actual schema of the "view" are owned by different database roles and that's why we are getting this error.As a work-around, I am thinking of making "dbo" user as the owner of both the schemas (base table and indexed view schema) and then grant full permission to database roles of "base table" and "indexed view" on their respective schemasQuestion: Does this approach has any security concerns when all the schemas will be owned by dbo user ?Thanks in advance,Vikas

Quirky Update in SQL 2012

$
0
0
All,is the "Quirky Update" hole is still open in sql 2012 shop too? or is there any patch applied to close the hole?if yes, what is the workaround for this? I remember Jeff mentioned in one of his interview this was closed. But i am not sure.

Help On Query

$
0
0
[code="plain"]create table Sample(Name Varchar(100),Role Varchar(10))insert into Sample values ('Vignesh' , 'Admin')insert into Sample values ('Vignesh' , 'User')insert into Sample values ('Bala' , 'Admin')insert into Sample values ('Bala' , 'User')insert into Sample values ('Suresh' , 'Admin')insert into Sample values ('Arun' , 'User')[/code]1. In sample table there were 4 names Vignesh, Bala, arun & suresh2. There are 2 kinds of role (admin & user)3. Vignesh & bala have both the roles , arun & suresh have any one of the roleI need to find who are having both roles ..Kindly help..

FOR XML question

$
0
0
Hi,I use this code sometimes to illustrate which files duplicate records come from. It puts the email address in one column, and a comma separated list of IDs in another column. What I can't figure out is how to select ONLY records which have a comma in the ID column, so the non-duplicate records don't appear in the results. Whenever I try to do a WHERE col LIKE '%,%' I get an invalid column error, no matter how I seem to alias things. Do I need to put this query in a CTE or another SELECT to do that, or is there a way how it's set up now?[code="sql"]select distinct s2.email, substring((select ', '+ cast(s1.id as varchar(64))from dbo.j3688931 s1where s1.email = s2.emailorder by s1.idfor xml path ('')),2, 8000) [ids]from dbo.j3688931 s2[/code]Thanks

Query plan parameter run time value not appearing in sys.dm_exec_query_plan

$
0
0
Hello --- when looking at a simple query plan for a select with "Include Actual Execution Plan" enabled in sql server mgmt studio (SSMS), I see a ParameterCompiledValue in the XML plan as well as a ParameterRuntimeValue in it. However, if I capture this same query in another tab using sys.dm_exec_query_plan and providing the plan handle of the currently running select statement, I get the same plan, but it does *not* have the ParameterRuntimeValue. It only has ParameterCompiledValue. Otherwise the plan is the exact same. If I change up parameter values, I still see only the original ParameterCompiledValue via sys.dm_exec_query_plan but I can see both ParameterCompiledValue and the ParameterRuntimeValue when looking at SSMS "Include Actual Execution Plan" output. Any ideas why sys.dm_exec_query_plan does not show ParameterRuntimeValue? Thanks!

Help On Query

$
0
0
Hi Everybody,[code="plain"]Create Table #sample ( Name Varchar(100),Mark1 int,Mark2 int,Mark3 int)insert into #sample values ('Vignesh',100,59,95)insert into #sample values ('ram',23,45,33)insert into #sample values ('kumar',58,12,15)insert into #sample values ('umar',15,25,98) [/code]I need following output ...[code="plain"]select name,mark1,'mark1' from #sampleunion allselect name,mark2,'mark2' from #sampleunion allselect name,mark3,'mark3' from #sample [/code]Is there any dynamic query to produce this output?

How to Split An Incoming Array Parameter from VB6 into SQL Server 2012

$
0
0
I have a need of passing-in an array of email addresses from a VB6 application to SQL Server 2012 stored procedure, about 20 email addresses total per array, and they'll look basically like this as they come into the SQL Server stored procedure:"EmailOne@gmail.com;EmailTwo@gmail.com;EmailThree@gmail.com;EmailFour@gmail.com"... and so onWhat I basically would like to do within my SQL Server 2012 stored procedure is parse/split each of the individual email addresses contained in the array and run individual "Update" statements to indicate in a particular table that I've successfully sent an email to each of the approx. 20 email addresses.I know that I could loop through the array of 20-or-so email addresses within my VB6 application and call the SQL Server stored procedure 20 different times and do the updates to the records containing each email address in the array. However, I was curious if I could just pass all 20 email addresses, separated by the ";" delimiter as I showed in the example earlier, and do everything with *ONE* call to a stored procedure instead of 20 individual calls.Any suggestions or examples are much appreciated.Thanks.

Help on a complex query that may be easier than what we have??

$
0
0
Hello all.We have a solution to a problem but think there is a much easier way to do this...I was thinking a join with a "temp table....what we have is a "heiarchy" in a tree structure that can contain hundres of different items, each will have a version number, or a null as default. The example below shows one way to do it:select *FROM sometable where NodeId ='5100' and NodeVersion =1 and SUBSTRING(CICS,0, LEN('1.1')+1)<>'1.1'unionselect *FROM factTenderItemValue where NodeId ='5130.1.1' and NodeVersion =25100 is the "parent" of 5130....what we want is to recognize that 5130.1.1 version to has been selected (we do that in C#) and incluse all children of 5100 with a version number of 1 BUT exclude version 1 from 5300 and use the selected version #2.....the sql will be dynamically created via C#...whis does work but can produce hundreds of statements...Any ideas/suggetions welcomed....my thought was to populate an "#IWant" temp table and a join.....

store proc based logical issue

$
0
0
I have a job which runs a store procedure. The proc is something likeBEGINSTEP 1) Archive records into Table A..... (around 15K records)from TABLE BSTEP 2) Delete some records from the table BSTEP 3) Insert new records into Table BSTEP 4) Update table BENDThis proc takes about 20 mins to run.Jobs kicks at 7:15 and as soon as job starts i can not access records from TABLE B deleted in STEP 2. I know step 1 takes about 10 mins . My assumption was that SP has sequential processing and not parallel processing. Is it possible that it can run statement 2 along with step 1. I am confused about how it gets executed. I cant see execution plan and getting permission is like 10 day process.

Max Consecutive Dates Without an Exclusion Date

$
0
0
Here's one that's been nagging me.I've got two tables, with date "ranges." Table A is an "order" with a start / end range, the related table B is an exclusion date range table, which could have many exclusion ranges per "order."[b]Table A[/b][b]OrderID, StartDate, EndDate[/b]14,'2013-09-13','2013-10-01'[b]Table BOrderID, ExclusionStart, ExclusionEnd[/b]14, '2013-09-14','2013-09-15'14, '2013-09-21','2013-09-22'14, '2013-09-28','2013-09-29'14, '2013-09-25','2013-09-25'[b]Sample setup:[/b][code="sql"]CREATE TABLE [dbo].[OrderSample]( [OrderID] [int] , [OrderStartDate] [datetime] , [OrderEndDate] [datetime])--## Create sample 'order'INSERT INTO OrderSample VALUES(14,'2013-09-01','2013-09-30')CREATE TABLE [dbo].[ExclusionSample]( [OrderID] [int] , [ExclusionStartDate] [datetime] , [ExclusionEndDate] [datetime])--## Create sample 'exclusion ranges' - my product does not work these daysINSERT INTO ExclusionSample VALUES(14, '2013-09-14','2013-09-15')INSERT INTO ExclusionSample VALUES(14, '2013-09-21','2013-09-22')INSERT INTO ExclusionSample VALUES(14, '2013-09-28','2013-09-29')INSERT INTO ExclusionSample VALUES(14, '2013-09-25','2013-09-25')[/code]What's the best way to get the [b]MAX() consecutive valid days[/b] (uninterrupted by exclusion dates) per order? Desired Output:[b]Table Output[/b]OrderID, MaxConsecValidDatesMy current solution is to use a UDF to explode both ranges and get a full list of dates per OrderID in separate "staging" tables, then filter out the excluded dates from a "ValidOrderDates" table... And run a CTE over the top of that to return the consecutive days.This is slow at the outset to set up, even with relatively low (300/400k rows in each table) but manageable incrementally going forward. Is there a bigger/better/faster approach? Am I overlooking a way to do this in a set-based manner?Thank you for looking it over!

Msg 2812, Level 16, State 62, Line 2 Could not find stored procedure 'xml_schema_namespace'.

$
0
0
Hi,my version is sql server is as follow[code="sql"]SELECT @@VERSIONMicrosoft SQL Server 2012 - 11.0.2100.60 (X64) Feb 10 2012 19:39:15 Copyright (c) Microsoft Corporation Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)[/code]according to http://technet.microsoft.com/en-us/library/ms175562.aspx way of executing function and http://technet.microsoft.com/en-us/library/ms188332.aspx[code="sql"]DECLARE @ret nvarchar(max);EXEC @ret=xml_schema_namespace @Relational_schema=N'dbo' , @XML_schema_collection_name =N'MyCollection';PRINT @ret;I received the following error:[/code][code="sql"]Msg 2812, Level 16, State 62, Line 2Could not find stored procedure 'xml_schema_namespace'. [/code]May I know what's wrong?thanks

Trying to create line items records from a string

$
0
0
Hi all-I've got an invoice coming in as a single sting and am trying to figure out how to best break the string up into individual line item records:The string looks like this (disregard carriage returns):HEADER*CompanyA*CompanyB*5001*8/22/2009^CATEGORY*Parts*PRT^LINE*PartA*11^LINE*PartF*5^LINE*PartG*37^CATEGORY*Supplies*SUP^LINE*SupplyK*1^LINE*SupplyY*88^LINE*SupplyG*72^CATEGORY*Materials*MTR^LINE*MaterialQ*202^And I'm trying to get the resultant table to look like this:DATE | ToCompany | FromCompany |InvoiceNum | ItemCategory|ItemCategoryCode| ItemDescr|ItemCode8/22/2009 CompanyA CompanyB 5001 Parts PRT PartA 118/22/2009 CompanyA CompanyB 5001 Parts PRT PartF 5 8/22/2009 CompanyA CompanyB 5001 Parts PRT PartF 37 8/22/2009 CompanyA CompanyB 5001 Supplies SUP SupplyK 18/22/2009 CompanyA CompanyB 5001 Supplies SUP SupplyY 888/22/2009 CompanyA CompanyB 5001 Supplies SUP SupplyG 72 8/22/2009 CompanyA CompanyB 5001 Materials MTR MaterialQ 202Any suggestions would be GREATLY appreciated.ThanksNick

send_dbmail recipients from table

$
0
0
Hi All,my first post here maybe a newby one.Well,i have a table with data as from example below.statuscd|ordernum|name|date|email|sent|OK|22112233|john|17/09/2013|john@john.com|N|OK|56489161|mike|16/09/2013|mike@mike.com|N|......Idea is that i need to send an email to this recipients with sent flag N. For example john@john.com and to put in subject ordernum and statuscd and after that to update sent flag to Y because query will select data with flag N and send it again.This is recursive process because this table is refreshing every 15 minutes and email job will start every 10 minutes.Many thanks in advance.Regards
Viewing all 4901 articles
Browse latest View live