SQL将varchar变量与另一个varchar变量进行比较

时间:2016-06-11 17:30:14

标签: sql-server sql-server-2008

我有一个表名行,它有BillId(int)和LineReference(Varchar(100)作为两列。每个billid都有LineReference值。但是,LineReference中的值可能不正确。所以我必须验证LineReference来自已根据账单ID已经具有正确参考值的变量。

示例:

private Boolean buttonWasClicked = false;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        buttonWasClicked = true;



        if ( buttonWasClicked == true)
        {
         new SettingsWindow().Show();
        var test = new SettingsWindow();
        test.Owner = System.Windows.Application.Current.MainWindow;
        test.WindowStartupLocation = WindowStartupLocation.CenterOwner;
        test.Top = this.Top + 20;

        }
        else {

            buttonWasClicked = false;
        }


   }`

从上表中,我需要更新LineReference列。

Declare @iCountRef varchar(100) = 1,2,3

BillId   LineReference
100      1,2,
100      1,2,40,34
100      1
100      12

我只能通过与变量进行比较来更新:@iCountRef。 LineReference列应具有@iCountRef中的值。无论@CountRef中没有任何值,都应删除。如果没有匹配的值,则该列应至少更新为数字1。

2 个答案:

答案 0 :(得分:4)

1)在中期或长期,我想规范化这个数据库以避免这样的错误:在string / VARCHAR列中存储值列表。例如,我会使用以下多对多表:

CREATE TABLE dbo.BillItem (
    ID INT IDENTITY(1,1) PRIMARY KEY,
    BilldID INT NOT NOT NULL REFERENCES dbo.Bill(BilldID),
    ItemID INT NOT NULL REFERENCES dbo.Item(ItemID),
    UNIQUE (BillID, ItemID) -- Unique constraint created in order to prevent duplicated rows
);

在这种情况下,一个包含两个项目的账单意味着我必须在dbo.BillItem表中插入两行。

2)回到原始请求:对于一次性任务,我将使用XML和XQuery(此解决方案以SELECT语句结束,但转换为UPDATE很简单):

DECLARE @iCountRef VARCHAR(100) = '1,2,3'

DECLARE @SourceTable TABLE (
    BillId          INT,
    LineReference   VARCHAR(8000)
)

INSERT @SourceTable (BillId, LineReference)
VALUES
(100, '1,2,'),
(100, '1,2,40,34'),
(100, '1'),
(100, '12')

DECLARE @iCountRefAsXML XML = CONVERT(XML, '<a><b>' + REPLACE(@iCountRef, ',', '</b><b>') + '</b></a>')

SELECT  *, STUFF(z.LineReferenceAsXML.query('
    for $i in (x/y)
        for $j in (a/b)
            where data(($i/text())[1]) eq data(($j/text())[1])
        return concat(",", ($i/text())[1])
').value('.', 'VARCHAR(8000)'), 1, 1, '') AS NewLineReference
FROM (
    SELECT  *, CONVERT(XML, 
        '<x><y>' + REPLACE(LineReference, ',', '</y><y>') + '</y></x>' + 
        '<a><b>' + REPLACE(@iCountRef, ',', '</b><b>') + '</b></a>'
    ) AS LineReferenceAsXML
    FROM    @SourceTable s
) z

结果:

BillId      LineReference  NewLineReference LineReferenceAsXML                                                      
----------- -------------  ---------------- ------------------------------------------------------------------------
100         1,2,           1 ,2             <x><y>1</y><y>2</y><y /></x><a><b>1</b><b>2</b><b>3</b></a>             
100         1,2,40,34      1 ,2             <x><y>1</y><y>2</y><y>40</y><y>34</y></x><a><b>1</b><b>2</b><b>3</b></a>
100         1              1                <x><y>1</y></x><a><b>1</b><b>2</b><b>3</b></a>                          
100         12             (null)           <x><y>12</y></x><a><b>1</b><b>2</b><b>3</b></a>                         

答案 1 :(得分:2)

--Create temp table and inserting data:
DECLARE @BillsRefs TABLE (
    BillId int, 
    LineReference nvarchar(100)
)

INSERT INTO @BillsRefs VALUES
(100,      '1,2,'),
(100,      '1,2,40,34'),
(100,      '1'),
(100,      '12')

--Declare variables
DECLARE @iCountRef varchar(100) = '1,2,3',
        @xml xml, @iXml xml

--Convert @iCountRef in XML
SELECT @iXml = CAST('<b>' + REPLACE(@iCountRef,',','</b><b>') + '</b>' as xml)

--@iXml:
--<b>1</b>
--<b>2</b>
--<b>3</b>

--Convert table with data in XML
SELECT @xml = (
SELECT CAST('<s id="'+LineReference+'"><a>' + REPLACE(LineReference,',','</a><a>') + '</a></s>' as xml) 
FROM @BillsRefs
FOR XML PATH('')
)
--@xml:
--<s id="1,2,">
--  <a>1</a>
--  <a>2</a>
--  <a />
--</s>
--<s id="1,2,40,34">
--  <a>1</a>
--  <a>2</a>
--  <a>40</a>
--  <a>34</a>
--</s>
--<s id="1">
--  <a>1</a>
--</s>
--<s id="12">
--  <a>12</a>
--</s>

--Compare values from temp table to @iCountRef
--we convert string to xml - to convert them intoi tables
;WITH final AS (
SELECT DISTINCT
        t.v.value('../@id','nvarchar(100)') as LineReferenceOld, -- @id to take 'id="1,2,40,34"' from xml above
        CASE WHEN s.g.value('.','int') IS NULL THEN 1 ELSE s.g.value('.','int') END as LineReference 
        -- '.' is used to take value inside closed tags
FROM @xml.nodes('/s/a') as t(v) --we takes @xml (look above) and play with its nodes 's' (root for each @id) and `a`
LEFT JOIN @iXml.nodes('/b') as s(g) --we takes @iXml it has only 'b' tags
    ON t.v.value('.','int') = s.g.value('.','int') --here we JOIN both xml by `a` and `b`  tags
)

--In final table we get this:

--LineReferenceOld  LineReference
--1,2,              2
--12                    1
--1,2,40,34         1
--1,2,40,34         2
--1                 1
--1,2,              1

--Final SELECT
SELECT c.BillId,
        STUFF((SELECT DISTINCT  ','+CAST(f.LineReference as nvarchar(10))
        FROM final f
        WHERE c.LineReference = f.LineReferenceOld
        FOR XML PATH('')),1,1,'') as LineReference
FROM @BillsRefs c 

输出:

BillId  LineReference
100     1,2
100     1,2
100     1
100     1

如果您需要更新源表:

UPDATE c
SET LineReference = STUFF((SELECT DISTINCT  ','+CAST(f.LineReference as nvarchar(10))
        FROM final f
        WHERE c.LineReference = f.LineReferenceOld
        FOR XML PATH('')),1,1,'')
FROM @BillsRefs c