In SQL Server, I query data from two VIEW to get records whose OLDPID are -1,-2:
SELECT
T1.*, T2.LEAF
FROM
(SELECT *
FROM VIEW_OBJECT_TREE_DATA
WHERE OLDPID IN (-1, -2)) T1
LEFT JOIN
VIEW_OBJECT_TREE_DATA_GROUP T2 ON T1.NODEID = T2.NODEPID
WHERE
T1.STATE = 1
But it takes 3-4 seconds to get the result.
How can I modify this SQL query to improve its speed?
VIEW_OBJECT_TREE_DATA has OLDPID, OLDID and NAME columns with 450000 records.VIEW_OBJECT_TREE_DATA_GROUP has NODEPID and LEAF with 65000 records.
Below is some sql of view and function:
VIEW_OBJECT_TREE_DATA:
CREATE VIEW dbo.VIEW_OBJECT_TREE_DATA
AS
SELECT(SELECT[dbo].[FNNC_GET_TREE_GUID](0, OBJECT_ID)) AS NODEID,
(SELECT[dbo].[FNNC_GET_TREE_GUID](0, PARENT_ID)) AS NODEPID, 'MY_OBJECT_TABLE' AS[TABLE],
OBJECT_ID AS OLDID, PARENT_ID AS OLDPID, OBJECT_NAME COLLATE DATABASE_DEFAULT AS NAME,
OBJECT_CODE COLLATE database_default AS CODE, OBJECT_TYPE COLLATE database_default AS TYPE,
OBJECT_STATE as STATE
FROM dbo.MY_OBJECT_TABLE
WHERE OBJECT_STATE <> -1
UNION
SELECT(SELECT[dbo].[FNNC_GET_TREE_GUID](1, INDICATOR_ID)) AS NODEID,
(SELECT[dbo].[FNNC_GET_TREE_GUID](0, OBJECT_ID)) AS NODEPID, 'MY_INDICATOR_TABLE' AS[TABLE],
INDICATOR_ID AS OLDID, OBJECT_ID AS OLDPID, INDICATOR_NAME COLLATE DATABASE_DEFAULT AS NAME,
INDICATOR_CODE COLLATE database_default AS CODE, INDICATOR_TYPE COLLATE database_default AS TYPE,
INDICATOR_STATE AS STATE
FROM dbo.MY_INDICATOR_TABLE
WHERE INDICATOR_STATE <> -1
VIEW_OBJECT_TREE_DATA_GROUP :
CREATE VIEW VIEW_OBJECT_TREE_DATA_GROUP
AS
SELECT NODEPID,COUNT(0) AS LEAF FROM VIEW_OBJECT_TREE_DATA GROUP BY NODEPID
Function:
USE[MY_DATABASE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION[dbo].[FNNC_GET_TREE_GUID](#TYPE INT, #ID INT)
RETURNS UNIQUEIDENTIFIER
AS
BEGIN
RETURN CAST(CAST(#TYPE AS binary(4))+CAST(#ID AS varbinary(28)) AS UNIQUEIDENTIFIER)
END
You can directly join those two views without having to use a subquery.
select TD.*, DG.LEAF
from VIEW_OBJECT_TREE_DATA as TD
left join VIEW_OBJECT_TREE_DATA_GROUP as DG on DG.NODEPID = TD.NODEID
where TD.OLDPID in (-1, -2) and
TD.STATE = 1
Although without seeing those views and the execution plan there is no way of knowing what slows you down.
Related
Just wondering the best way to put this into a temp table and then join it.
IF EXISTS(SELECT LocId
FROM dbo.Locations WITH (NOLOCK)
WHERE SourceSystem = #SourceSystem
AND LocId IN (SELECT ListVal
FROM etopsuser.fnParseListToTable(#LocIdList, ';')) AND IsHot = 1)
BEGIN
Specifically trying to do it on this line of code
(SELECT ListVal
FROM etopsuser.fnParseListToTable(#LocIdList, ';')) AND IsHot = 1)
The NOLOCK is unrelated
You would create a temporary table just like any other table from a select:
SELECT ListVal
INTO #templist
FROM etopsuser.fnParseListToTable(#LocIdList, ';');
Then you would use it as:
SELECT l.LocId
FROM dbo.Locations l JOIN
#templist tl
ON l.LocId = tl.Listval
WHERE l.SourceSystem = #SourceSystem AND l.IsHot = 1
The best way to pass a list into a procedure is to use a Table Valued Parameter
CREATE TYPE dbo.List AS TABLE (ListVal varchar(255));
IF EXISTS(SELECT 1
FROM dbo.Locations l
WHERE l.SourceSystem = #SourceSystem
AND l.LocId IN (
SELECT ll.ListVal
FROM #LocIdList ll
) AND IsHot = 1)
Notes: Always use table references on every column, especially if subqueries are involved. Never use NOLOCK unless you are prepared for incorrect results. EXISTS ignores its SELECT, so SELECT 1 or SELECT NULL is standard.
Then you can pass in the table variable either from client code depending on language, or in T-SQL like this
DECLARE #list dbo.List;
INSERT #list (ListVal)
VALUES ('SomeValue');
EXEC YourProc #LocIdList = #list;
I have a table with text field. I want to select rows where text is in all caps. This code works as it should, and returns ABC:
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE
txt COLLATE SQL_Latin1_General_CP1_CS_AS = UPPER(txt)
then I create UDF (as suggested here):
CREATE FUNCTION [dbo].[fnsConvert]
(
#p NVARCHAR(2000) ,
#c NVARCHAR(2000)
)
RETURNS NVARCHAR(2000)
AS
BEGIN
IF ( #c = 'SQL_Latin1_General_CP1_CS_AS' )
SET #p = #p COLLATE SQL_Latin1_General_CP1_CS_AS
RETURN #p
END
and run it as follows (which looks like an equivalent code to me):
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE
dbo.fnsConvert(txt, 'SQL_Latin1_General_CP1_CS_AS') = UPPER(txt)
however, this returns ABC as well as cdf.
Why is that so, and how do I get this to work?
PS I need UDF here to be able to call case-sensitive comparison from .Net LINQ2SQL provider.
A variable cannot have it's own collation. It will always use the server's default. Check this:
--I declare three variables, each of which get's its own collation - at least one might think so:
DECLARE #deflt VARCHAR(100) = 'aBc'; --Latin1_General_CI_AS in my system
DECLARE #Arab VARCHAR(100) = 'aBc' COLLATE Arabic_100_CS_AS_WS_SC;
DECLARE #Rom VARCHAR(100) = 'aBc' COLLATE Romanian_CI_AI
--Now check this. All three variables are seen as the system's default collation:
SELECT [name], system_type_name, collation_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT #deflt AS Deflt, #Arab AS Arab, #Rom AS Rom'
,N'#deflt varchar(100), #Arab varchar(100),#Rom varchar(100)'
,0);
/*
name system_type_name collation_name
Deflt varchar(100) Latin1_General_CI_AS
Arab varchar(100) Latin1_General_CI_AS
Rom varchar(100) Latin1_General_CI_AS
*/
--Now we check a simple comparison of "aBc" against "ABC"
SELECT CASE WHEN #deflt = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckDefault
,CASE WHEN #Arab = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckArab
,CASE WHEN #Rom = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckRom
/*CI CI CI*/
--But we can specify the collation for one given action!
SELECT CASE WHEN #deflt = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckDefault
,CASE WHEN #Arab = 'ABC' COLLATE Arabic_100_CS_AS_WS_SC THEN 'CI' ELSE 'CS' END AS CheckArab
,CASE WHEN #Rom = 'ABC' COLLATE Romanian_CI_AI THEN 'CI' ELSE 'CS' END AS CheckRom
/*CI CS CI*/
--But a table's column will behave differently:
CREATE TABLE #tempTable(deflt VARCHAR(100)
,Arab VARCHAR(100) COLLATE Arabic_100_CS_AS_WS_SC
,Rom VARCHAR(100) COLLATE Romanian_CI_AI);
INSERT INTO #tempTable(deflt,Arab,Rom) VALUES('aBc','aBc','aBc');
SELECT [name], system_type_name, collation_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT * FROM #tempTable',NULL,0);
DROP TABLE #tempTable;
/*
name system_type_name collation_name
deflt varchar(100) Latin1_General_CI_AS
Arab varchar(100) Arabic_100_CS_AS_WS_SC
Rom varchar(100) Romanian_CI_AI
*/
--This applys for declared table variables also. The comparison "knows" the specified collation:
DECLARE #TableVariable TABLE(deflt VARCHAR(100)
,Arab VARCHAR(100) COLLATE Arabic_100_CS_AS_WS_SC
,Rom VARCHAR(100) COLLATE Romanian_CI_AI);
INSERT INTO #TableVariable(deflt,Arab,Rom) VALUES('aBc','aBc','aBc');
SELECT CASE WHEN tv.deflt = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckDefault
,CASE WHEN tv.Arab = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckArab
,CASE WHEN tv.Rom = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckRom
FROM #TableVariable AS tv
/*CI CS CI*/
UPDATE Some documentation
At this link You can read about the details. A collation does not change the value. It applys a rule (related to NOT NULL which does not change the values, but just adds the rule whether NULL can be set or not).
The documentation tells clearly
Is a clause that can be applied to a database definition or a column definition to define the collation, or to a character string expression to apply a collation cast.
And a bit later you'll find
Creating or altering a database
Creating or altering a table column
Casting the collation of an expression
UPDATE 2: A suggestion for a solution
If you want to have control whether a comparison is done CS or CI you might try this:
DECLARE #tbl TABLE(SomeValueInDefaultCollation VARCHAR(100));
INSERT INTO #tbl VALUES ('ABC'),('aBc');
DECLARE #CompareCaseSensitive BIT = 0;
DECLARE #SearchFor VARCHAR(100) = 'aBc';
SELECT *
FROM #tbl
WHERE (#CompareCaseSensitive=1 AND SomeValueInDefaultCollation=#SearchFor COLLATE Latin1_General_CS_AS)
OR (ISNULL(#CompareCaseSensitive,0)=0 AND SomeValueInDefaultCollation=#SearchFor COLLATE Latin1_General_CI_AS);
With #CompareCaseSensitive set to 1 it will return just the aBc, with NULL or 0 it will return both lines.
This is - for sure! - much better in performance than an UDF.
Please try using BINARY_CHECKSUM Function, and no need to UDF Function:
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE
BINARY_CHECKSUM(txt)= BINARY_CHECKSUM(UPPER(txt))
I think you are confused on how collation works. If you want to force a case sensitive collation you would do it in your where predicate, not with a function like that. And scalar functions are horrible for performance.
Here is how you would be able to use collation for this type of thing.
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE txt collate SQL_Latin1_General_CP1_CS_AS = UPPER(txt)
Here's what I did:
I changed the function to perform a comparison, instead of setting the collation, and then return a 1 or 0.
CREATE FUNCTION [dbo].[fnsConvert]
(
#p NVARCHAR(2000) ,
#c NVARCHAR(2000)
)
RETURNS BIT
AS
BEGIN
DECLARE #result BIT
IF ( #c = 'SQL_Latin1_General_CP1_CS_AS' )
BEGIN
IF #p COLLATE SQL_Latin1_General_CP1_CS_AS = UPPER(#p)
SET #result = 1
ELSE
SET #result = 0
END
ELSE
SET #result = 0
RETURN #result
END
Then the query that uses the function changes just a bit.
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE
dbo.fnsConvert(txt, 'SQL_Latin1_General_CP1_CS_AS') = 1
As #Shnugo stated, the collation is not an attribute of a variable, but it can be attribute of a column definition.
For collation-enabled comparison outside of TSQL, you can define a (persisted) computed column with an explicit collation:
create table Q47890189 (
txt nvarchar(100),
colltxt as txt collate SQL_Latin1_General_CP1_CS_AS persisted
)
insert into Q47890189 (txt) values ('ABC')
insert into Q47890189 (txt) values ('cdf')
select * from Q47890189 where txt = UPPER(txt)
select * from Q47890189 where colltxt = UPPER(colltxt)
Note that a persisted column can also be indexed, and has a better performance than calling a scalar function.
COLLATE :Is a clause that can be applied to a database definition or a column definition to define the collation, or to a character string expression to apply a collation cast.
COLLATE do not convert any column or variable..It define the characteristics of collate.
CREATE TABLE [dbo].[OINV]
[CardCode] [nvarchar](50) NULL
)
if i have a table with 5175460 rows
then converting this to another data type will take time because its of its value is converted to new data type.
alter table OINV
alter column CardCode varchar(50)
--1 min 45 sec
alter table OINV
alter column CardCode nvarchar(50) COLLATE SQL_Latin1_General_CP1_CS_AS
If i don't convert the data type and only want to change collate
then it take 1 ms to do so.That means it do not convert 5175460 rows to said collate.
It just define the collate on that column.
when this column is use in where condition then column will exhibit characteristics of said collate.
UDF/TVF is not perform-ant way to do so.Best way is to alter table
Another example,
declare #i varchar(60)='ABC'
SELECT txt
FROM (SELECT 'abc' AS txt UNION SELECT 'cdf') t
WHERE
txt = #i COLLATE SQL_Latin1_General_CP1_CS_AS
I can't declare it like this,
declare #i varchar(60) COLLATE SQL_Latin1_General_CP1_CS_AS='ABC'
So variable will exhibit collate characteristics only as long as it is use along collate .
In your case you are return only plain variable,
UDF way of doing so,
CREATE FUNCTION testfn (
#test VARCHAR(100)
,#i INT
)
RETURNS TABLE
AS
RETURN (
-- insert into #t values(#test)
SELECT #test COLLATE SQL_Latin1_General_CP1_CS_AS AS a
)
SELECT *
FROM (
SELECT 'ABC' AS txt
UNION
SELECT 'cdf'
) t
OUTER APPLY dbo.testfn(txt, 0) fn
WHERE fn.a = UPPER(txt)
To define multiple collate you have to define multiple table with different collate. TVF can return only static table schema,so there can be only one collate define.
Therefore TVF is not right way to perform your task.
I agree with #Shnugo when you create local variable it will take default collation
But, you could explicitly collate your variable values returned by function with your user defined collation as follow :
select * from
(SELECT 'ABC' AS txt UNION SELECT 'cdf') a
where (dbo.fnsConvert(txt, 'SQL_Latin1_General_CP1_CS_AS')
collate SQL_Latin1_General_CP1_CS_AS) = UPPER(txt)
In addition collate clause can only applied to database definition, column defination or string/character expression, in other words it is used for database objects i.e. tables, columns, indexes
collation_name can't be represented by variable or expression.
MSDN clearly defines COLLATE:
Is a clause that can be applied to a database definition or a column
definition to define the collation, or to a character string
expression to apply a collation cast.
Can you see a word about variable here?
If you need UDF, just use table-valued function:
CREATE FUNCTION dbo.test
(
#text nvarchar(max)
)
RETURNS TABLE
AS
RETURN
(
SELECT c COLLATE SQL_Latin1_General_CP1_CS_AS as txt
FROM (VALUES (#text)) as t(c)
)
GO
And use it like:
;WITH cte AS (
SELECT N'ABC' as txt
UNION
SELECT N'cdf'
)
SELECT c.txt
FROM cte c
OUTER APPLY dbo.test (c.txt) t
WHERE t.txt = UPPER(c.txt)
Output:
txt
------
ABC
The following query works perfectly,
insert into [EGallery].dbo.[CustomerDetails]
Select Distinct B.CountyB as 'Mobile' , Cast(BuildingB as Varchar(100)) as 'Email' ,
A.CardCode , A.CardName as 'First Name' , '' as 'Last Name' ,
'' as Gender , Cast(A.Address as Varchar(1000)) as 'Address' , Convert(Varchar(10), A.U_BirthDay,105) as 'birthday' ,
Convert(Varchar(10), A.U_AnnivDay ,105) as 'Anniversary' ,
Case
When A.CardCode Like '%%'+ C.WhsCode +'%%' Then Convert(Varchar(10) , A.DocDate ,105)
Else Convert(Varchar(10), (Select X.CreateDate From OCRD X Where X.CardCode = A.CardCode) ,105) End as 'JoinDate' ,
C.WhsCode as 'JoinStore','Open' as Status ,(Select GETDATE()) as CreatedDateTime,(Select GETDATE()) as ProcessDateTime, '' as StatusMSg
From OINV A
Inner Join INV12 B On A.DocEntry = B.DocEntry
Inner Join INV1 C On A.DocEntry = C.DocEntry
Where C.LineNum = '0'
--B.CountyB not in(select D.Mobile from [EGallery].dbo.[CustomerDetails] D where D.Mobile=B.CountyB)
--not exists (select Mobile from [EGallery].dbo.[CustomerDetails] D where D.Mobile=B.CountyB)
But before I insert records into the [EGallery].dbo.[CustomerDetails] table, I need to check whether the phone number already exists in the table. If the record already exists, there is no need to insert it again. For that I have added one more condition (which I have commented out in the query) but it reports this error while running the query:
Cannot resolve the collation conflict between "SQL_Latin1_General_CP850_CI_AS" and "Latin1_General_CI_AI" in the equal to operation.
According to here you have to add COLLATE DATABASE_DEFAULT to the queries like this:
Where C.LineNum = '0' AND
B.CountyB not in(select D.Mobile from [EGallery].dbo.[CustomerDetails] D where D.Mobile COLLATE DATABASE_DEFAULT = B.CountyB COLLATE DATABASE_DEFAULT) AND
not exists (select Mobile from [EGallery].dbo.[CustomerDetails] D where D.Mobile COLLATE DATABASE_DEFAULT = B.CountyB COLLATE DATABASE_DEFAULT)
Try to do this before your query:
USE [db name for object INV12]
GO
ALTER TABLE [EGallery].dbo.[CustomerDetails]
ALTER COLUMN Mobile
VARCHAR(100) COLLATE Latin1_General_CI_AS NOT NULL
ALTER TABLE INV12
ALTER COLUMN CountyB
VARCHAR(100) COLLATE Latin1_General_CI_AS NOT NULL
UPDATE1:
If you have an index on one of this columns, or on both of them, you need to delete it and create index again after a new collation will be changed.
I recommend you to use a MERGE statement, as it
performs insert, update, or delete operations on a target table based on the results of a join with a source table. For example, you can synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table.
So this is bit confusing. I already have a stored procedure. I have report which has 5 to 6 parameters. I want it to run the report in such a way that you should be able to select multiple values in the drop down and also keep it optional(not select any values). Other thing is that my parameter value also has NULL values which I have replaced it with NA. I tried using Default Value in the Parameter properties for some selection it works and for some selection it does not. I am still an intermediate person working on SSRS. Any help will be greatly appreciated.
Thanks
I am assuming that you have created a function and used that function in stored procedure to make that stored procedure as multi value selection.
In your function Whichever variable has varchar or any string data type make their size to MAX like varchar(max) and also do the same thing in Stored procedure for parameter.
Reason behind this one: When you provide the data type as varchar(255) it will just take a value for 255 character and if your value character is exceeding that limit then it will truncate the data which is exceeding that limit. And you are making them multi select so probably you need to make them as varchar(max).
Also make the size as Max in stored procedure for parameter.
Note: Varchar(Max) is just an example. You can provide max to any string data type that you have used in function and stored procedure.
Let me know if it works..
ALTER PROCEDURE [dbo].[sp_PIMSelect_AJ_Test]
#network nvarchar(MAX),
--#provider nvarchar(MAX),
--#affiltype varchar(MAX),
--#npi varchar(MAX),
--#tin varchar(MAX),
--#inprovtype varchar (MAX),
#SLG nvarchar(MAX),
#county nvarchar(MAX),
#zip nvarchar(Max),
#specCode nvarchar(Max),
#affiltype nvarchar(Max),
#contract nvarchar(Max)
AS
SET NOCOUNT ON;
select * from (
select
distinct P1.Provid as PIMProviderID,
P.NetworkName,
--COALESCE(pa.affiltype, 'NA') as affiliationtype,
PP1.planprovid as ProviderPlanProvID,
p1.lastname as ProviderLastName,
p1.Firstname as ProviderFirstName,
P1.Profdesig as ProviderTitle,
p1.intprovtype as ProviderIntProvType,
COALESCE(NULLIF(P1.Provtype, ''), 'NA') as ProviderProvType,
XP1.Description as ProviderTypeDescription,
COALESCE(ps1.specialtycode, 'NA') as ProviderSpecialtyCode,
ps1.DirectorySpec as ProviderSpecialityDescription,
ps1.spectype as ProviderSpecType,
p1.CredType as ProviderCredType,
p1.phyaddress1 as ProviderPhyAddress1,
p1.phyaddress2 as ProviderPhyAddress2,
p1.phycity as ProviderPhyCity,
p1.phystate as ProviderPhyState,
p1.phyzipcode as ProviderPhyZipCode,
p1.phycounty as ProviderPhyCounty,
p1.address1 as ProviderMailingAddress1,
p1.address2 as ProviderMailingAddress2,
p1.city as ProviderMailingCity,
p1.state as ProviderMailingState,
p1.Zipcode as ProviderMailingZip,
p1.county as ProviderMailingCounty,
COALESCE(NULLIF(p1.TIN, ''),'0') as ProviderTIN,
COALESCE(NULLIF(p1.NPI, ''),'0') as ProviderNPI,
pa.Affiltype as AffilType,
p.provid as AffilPIMProviderID,
PP.planprovid as AffiliationPlanProvID,
p.Lastname as AffilLastName,
p.Firstname as AffilFirstName,
COALESCE(p.intprovtype, 'NA') as AffilIntProvType,
XP.Description as AffiliationTypeDescription,
ps.specialtycode as AffilSpecialtyCode,
ps.spectype as AffilSpecType,
ps.directoryspec as AffilSpecialtyDescription,
PA.IntDirLocation as AffilDirLocation,
p.phyaddress1 as AffilPhyAddress1,
p.phyaddress2 as AffilPhyAddress2,
p.phycity as AffilPhyCity,
p.phystate as AffilPhyState,
COALESCE(NULLIF(p.phyzipcode, ''), 'NA') as AffilPhyZipCode,
COALESCE(NULLIF(p.phycounty, ''), 'NA') as AffilPhyCounty,
p.address1 as AffilMailingAddress1,
p.address2 as AffilMailingAddress2,
p.city as AffilMailingCity,
p.state as AffilMailingState,
p.Zipcode as AffilMailingZip,
p.county as AffilMailingCounty,
COALESCE(NULLIF(p.TIN, ''),'0') as AffilTIN,
COALESCE(NULLIF(p.NPI, ''),'0') as AffilNPI,
COALESCE(CI.contractid, 'NA') as AffilContractID,
COALESCE(C.description, 'NA') as AffilContractDesc
from ProviderManager.dbo.Provider p
left join ProviderManager.dbo.XProviderTypes XP on P.Provtype = XP.[Provider Type_ID]
left join ProviderManager.dbo.planprovinfo PP on P.Provid = PP.provid
left join ProviderManager.dbo.provspecialty ps on ps.provid = p.Provid
left join ProviderManager.dbo.Affiliation pa on pa.affilid= p.Provid
left join ProviderManager.dbo.provider p1 on p1.provid = pa.provid
left join ProviderManager.dbo.CredApproval CA on P1.NPI = CA.NPI
left join ProviderManager.dbo.planprovinfo PP1 on P1.Provid = PP1.provid
left join ProviderManager.dbo.provspecialty ps1 on p1.Provid = ps1.provid
left join ProviderManager.dbo.XProviderTypes XP1 on P1.Provtype = XP1.[Provider Type_ID]
left join ProviderManager.dbo.contractinfo CI on P1.Provid = CI.provid and P.intprovtype = 'Group' and P.Provid = CI.affilid
left join ProviderManager.dbo.Contract C on CI.contractid
COLLATE SQL_Latin1_General_CP1_CI_AS = C.contractid COLLATE SQL_Latin1_General_CP1_CI_AS) cte
WHERE
cte.ProviderIntProvType IN ('Facility', 'Physician')
and (cte.NetworkName COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#network, ',')))
and (cte.AffilPIMProviderID IN (Select Value from VIB_Extracts.dbo.FnSplit(#SLG, ',')))
and (cte.AffilPhyCounty COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#county, ','))OR (#county = 'NA'))
and (cte.Affilphyzipcode COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#zip, ',')) OR (#zip = 'NA'))
and (cte.ProviderSpecialtyCode COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#specCode, ',')))
and (cte.ProviderProvType COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#affiltype, ',')))
and (cte.AffilContractID COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#contract, ',')))
--and (cte.providerNPI COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#npi,',')))
--and (cte.providerTIN COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#TIN,',')))
Order by Cte.ProviderLastName
USE [VIB_Extracts]
GO
/****** Object: UserDefinedFunction [dbo].[FnSplit] Script Date: 4/29/2017 9:59:16 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[FnSplit]
(
#List nvarchar(MAX),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Value nvarchar(100)
)
AS
BEGIN
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
I made a lot of views with 7-20 columns in each of them. I need to make a query which will return me the list of tables and columns on which is related every column in every view.
Example of my view:
CREATE VIEW example AS
SELECT t.NAME, t.AGE, t.ADDRESS, p.MOBILE, p.LAPTOP ...
FROM person t, device p
WHERE ...
Query result (needed):
TABLE COLUMN
person NAME
person AGE
person ADDRESS
device MOBILE
device LAPTOP
Is this possible, and how? It saves me a lot of time (there is over 900 columns in all views).
Thanks
Yet you can have this query to pull all the views present in your database along with columns present in them views.
SELECT v.name AS View_Name
,c.name AS Column_Name
FROM sys.views v
INNER JOIN sys.all_columns c ON v.object_id = c.object_id
Here is a more elaborated solution, the idea is to convert views to temp tables with no records (select top 0 * from ...) and for each table retrieve the column names from INFORMATION SCHEMA:
---Create this table First
CREATE TABLE dbo.Views_Columns(
id INT IDENTITY(1,1) PRIMARY KEY,
ViewName varchar(100),
ColumnName varchar(100)
)
--START
DECLARE #CurrentView varchar(100)
DECLARE #CurrentSchema varchar(50)
--Temp table #AllViews stores all views names
SELECT s.name as SchemaName, v.name as ViewName, 0 as Processed
INTO #AllViews
FROM sys.views v INNER JOIN SYS.schemas s ON v.schema_id = s.schema_id
WHILE EXISTS (select * from #AllViews WHERE Processed = 0)
BEGIN
--Clean up our temp table
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'temp')
BEGIN
DROP TABLE dbo.temp
END
SELECT TOP 1 #CurrentView = ViewName, #CurrentSchema = SchemaName
FROM #AllViews WHERE Processed = 0
EXEC('SELECT TOP 0 * INTO dbo.temp FROM '+#CurrentSchema+'.'+#CurrentView)
INSERT INTO Views_Columns
SELECT #CurrentSchema+'.'+#CurrentView, Column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'temp'
UPDATE #AllViews SET Processed = 1 where ViewName = #CurrentView
END
SELECT * FROM Views_Columns
--END